SlideShare a Scribd company logo
•
•
•
•
• @MOCKITOGUY
•
•
•
•
•
•
•
•
•
•
•
•
•
• SUPPORTED BY OBJENESIS
•
MOCK
MOCK
YAGNI
•
•
•
private static final String USER = ”user123";
private static final String PASSWORD = ”pass123
@Test
public void testLoginSucess(){
LoginController loginBean = new LoginController();
LoginResponse outcome = loginBean.login(USER,PASSWORD);
Assert.assertEquals("Test Sucess login",true,outcome.isLoged());
}
Write a test for your controller as clean and simple as possible it doesn't need
pass or even compile
• Problem:
• Client have their own login service witch integration layer is not ready yet.
• You need to invoke login integration layer to perform login.
• Solution:
• Create a login integration mock.
• Inject login integration mock into loginController
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.15.0</version>
<scope>test</scope>
</dependency>
authenticatorMock = mock(AuthenticatorInterface.class);
loginBean.setAutenticator(authenticatorMock);
when(authenticatorMock.login(USER,PASSWORD)).thenReturn(true);
Given user perform login then audit login attempt
verify(authenticatorMock,atLeastOnce()).audit(USER,"BEGIN");
Given user perform login when credentials are correct then audit login success
verify(authenticatorMock,atLeastOnce()).audit(USER,"SUCESS")
Check the execution order of your class, in real implementation even!
InOrder inOrder = inOrder(authenticatorMock);
inOrder.verify(authenticatorMock,atLeastOnce()).audit(USER,"BEGIN");
inOrder.verify(authenticatorMock,times(1)).login(USER,PASSWORD);
inOrder.verify(authenticatorMock, atLeast(1)).audit(USER,"SUCESS");
Given user perform login when credentials are correct then send mail notification
verify(loginBean,times(1)).notifyEvent(USER,"SUCESS");
loginBean = spy(new LoginController());
Given user perform login when credentials are not correct then return false
Given user perform login when password is not valid then return IllegalArgumentException
when(authenticatorMock.login(USER,null))
.thenThrow(new IllegalArgumentException());
Create an argument matcher and make more BDD like
given(authenticatorMock.login(eq(USER), argThat(invallidPassword )))
.willThrow(new IllegalArgumentException());
private static ArgumentMatcher<String> invallidPassword = new ArgumentMatcher<String>() {
public boolean matches(String s) {
return //implement your argument validator;
}
};
Given user perform login when credentials are correct
then return login menu and last login date.
Assert.assertEquals("verify user info size",2,outcome.getUserInfo().size());
private Answer sucessAnswer = new Answer<HashMap<String, Object>>() {
public HashMap<String, Object> answer(InvocationOnMock invocationOnMock) throws Throwable {
HashMap<String, Object> userInfo = new HashMap<String, Object>();
//create your custom answer
return userInfo;
}
};
when(dataProviderMock.getUserInfo(USER))
.thenAnswer(sucessAnswer);
Mockito PowerMock
2.8.0-2.8.9 1.7.x
2.7.5 1.7.0RC4
2.4.0 1.7.0RC2
1.10.8 - 1.10.x 1.6.2 - 2.0
1.9.5-rc1 - 1.9.5 1.5.0 - 1.5.6
1.8.5 1.3.9 - 1.4.9
1.8.4 1.3.7 & 1.3.8
1.8.3 1.3.6
1.8.1 & 1.8.2 1.3.5
1.8 1.3
Private field? -> Whitebox.setInternalState(loginBean, "dataProvider", dataProviderMock);
Static method? -> mockStatic(LoginController.class);
@RunWith(PowerMockRunner.class)
@PrepareForTest(LoginController.class)
public class LoginControllerTest {
}
Avoid constructor -> Whitebox.newInstance(LoginController.class)
Avois static inizializer -> @SuppressStaticInitializationFor("com.jug.mockito.LoginController")
Avoid method -> suppress(method(LoginController.class, "notifyAllNodes"))
https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior
https://github.com/powermock/powermock/wiki/Mockito
https://github.com/mockito/mockito/wiki

More Related Content

What's hot

Opensocial Codelab
Opensocial CodelabOpensocial Codelab
Opensocial Codelab
Pieter De Schepper
 
Chapter 11
Chapter 11Chapter 11
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB
 
CloudBrew: Windows Azure Mobile Services - Next stage
CloudBrew: Windows Azure Mobile Services - Next stageCloudBrew: Windows Azure Mobile Services - Next stage
CloudBrew: Windows Azure Mobile Services - Next stage
Teemu Tapanila
 
Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)
Joao Lucas Santana
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
State management in asp
State management in aspState management in asp
State management in asp
Ibrahim MH
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
Aravindharamanan S
 
Rolebased security
Rolebased securityRolebased security
Rolebased security
Sudhanshu Kumar
 
JS Conf 2018 AU Node.js applications diagnostics under the hood
JS Conf 2018 AU Node.js applications diagnostics under the hoodJS Conf 2018 AU Node.js applications diagnostics under the hood
JS Conf 2018 AU Node.js applications diagnostics under the hood
Nikolay Matvienko
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation framework
saqibsarwar
 
From mvc to viper
From mvc to viperFrom mvc to viper
From mvc to viper
Krzysztof Profic
 
Visual studio 2008 asp net
Visual studio 2008 asp netVisual studio 2008 asp net
Visual studio 2008 asp net
Portal_do_Estudante_SQL
 
Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity Container
Mindfire Solutions
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Frédéric Harper
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
Haim Michael
 
Application Frameworks - The Good, The Bad & The Ugly
Application Frameworks - The Good, The Bad & The UglyApplication Frameworks - The Good, The Bad & The Ugly
Application Frameworks - The Good, The Bad & The Ugly
Richard Lord
 

What's hot (18)

Opensocial Codelab
Opensocial CodelabOpensocial Codelab
Opensocial Codelab
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
CloudBrew: Windows Azure Mobile Services - Next stage
CloudBrew: Windows Azure Mobile Services - Next stageCloudBrew: Windows Azure Mobile Services - Next stage
CloudBrew: Windows Azure Mobile Services - Next stage
 
Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)Desenvolvimento web com Ruby on Rails (extras)
Desenvolvimento web com Ruby on Rails (extras)
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
State management in asp
State management in aspState management in asp
State management in asp
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
Rolebased security
Rolebased securityRolebased security
Rolebased security
 
JS Conf 2018 AU Node.js applications diagnostics under the hood
JS Conf 2018 AU Node.js applications diagnostics under the hoodJS Conf 2018 AU Node.js applications diagnostics under the hood
JS Conf 2018 AU Node.js applications diagnostics under the hood
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation framework
 
From mvc to viper
From mvc to viperFrom mvc to viper
From mvc to viper
 
Visual studio 2008 asp net
Visual studio 2008 asp netVisual studio 2008 asp net
Visual studio 2008 asp net
 
Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity Container
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
 
Application Frameworks - The Good, The Bad & The Ugly
Application Frameworks - The Good, The Bad & The UglyApplication Frameworks - The Good, The Bad & The Ugly
Application Frameworks - The Good, The Bad & The Ugly
 

Similar to Mockito junit

Agile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoAgile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Moldova ICT Summit
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
Sviatkin Yaroslav
 
Creating a Facebook Clone - Part XXVIII - Transcript.pdf
Creating a Facebook Clone - Part XXVIII - Transcript.pdfCreating a Facebook Clone - Part XXVIII - Transcript.pdf
Creating a Facebook Clone - Part XXVIII - Transcript.pdf
ShaiAlmog1
 
Spring Security.ppt
Spring Security.pptSpring Security.ppt
Spring Security.ppt
Patiento Del Mar
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QAFest
 
Creating a Whatsapp Clone - Part XIII - Transcript.pdf
Creating a Whatsapp Clone - Part XIII - Transcript.pdfCreating a Whatsapp Clone - Part XIII - Transcript.pdf
Creating a Whatsapp Clone - Part XIII - Transcript.pdf
ShaiAlmog1
 
JavaEE Security
JavaEE SecurityJavaEE Security
JavaEE Security
Alex Kim
 
ERRest
ERRestERRest
ERRest
WO Community
 
InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)
Andrea Bizzotto
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
FIDO Alliance
 
JSRs 303 and 330 in Action
JSRs 303 and 330 in ActionJSRs 303 and 330 in Action
JSRs 303 and 330 in Action
simonetripodi
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
Dmitry Buzdin
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
GlobalLogic Ukraine
 
Jsr 303
Jsr 303Jsr 303
Android Testing
Android TestingAndroid Testing
Android Testing
Evan Lin
 
jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010
mennovanslooten
 
Lesson_07_Spring_Security_Login_NEW.pdf
Lesson_07_Spring_Security_Login_NEW.pdfLesson_07_Spring_Security_Login_NEW.pdf
Lesson_07_Spring_Security_Login_NEW.pdf
Scott Anderson
 
Creating a Whatsapp Clone - Part XIII.pdf
Creating a Whatsapp Clone - Part XIII.pdfCreating a Whatsapp Clone - Part XIII.pdf
Creating a Whatsapp Clone - Part XIII.pdf
ShaiAlmog1
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard Learn
Dan Rinzel
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
Knoldus Inc.
 

Similar to Mockito junit (20)

Agile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoAgile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai Shevchenko
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
Creating a Facebook Clone - Part XXVIII - Transcript.pdf
Creating a Facebook Clone - Part XXVIII - Transcript.pdfCreating a Facebook Clone - Part XXVIII - Transcript.pdf
Creating a Facebook Clone - Part XXVIII - Transcript.pdf
 
Spring Security.ppt
Spring Security.pptSpring Security.ppt
Spring Security.ppt
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
 
Creating a Whatsapp Clone - Part XIII - Transcript.pdf
Creating a Whatsapp Clone - Part XIII - Transcript.pdfCreating a Whatsapp Clone - Part XIII - Transcript.pdf
Creating a Whatsapp Clone - Part XIII - Transcript.pdf
 
JavaEE Security
JavaEE SecurityJavaEE Security
JavaEE Security
 
ERRest
ERRestERRest
ERRest
 
InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)InheritedWidget is your friend - GDG London (2018-08-08)
InheritedWidget is your friend - GDG London (2018-08-08)
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
 
JSRs 303 and 330 in Action
JSRs 303 and 330 in ActionJSRs 303 and 330 in Action
JSRs 303 and 330 in Action
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
 
Jsr 303
Jsr 303Jsr 303
Jsr 303
 
Android Testing
Android TestingAndroid Testing
Android Testing
 
jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010jQuery Bay Area Conference 2010
jQuery Bay Area Conference 2010
 
Lesson_07_Spring_Security_Login_NEW.pdf
Lesson_07_Spring_Security_Login_NEW.pdfLesson_07_Spring_Security_Login_NEW.pdf
Lesson_07_Spring_Security_Login_NEW.pdf
 
Creating a Whatsapp Clone - Part XIII.pdf
Creating a Whatsapp Clone - Part XIII.pdfCreating a Whatsapp Clone - Part XIII.pdf
Creating a Whatsapp Clone - Part XIII.pdf
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard Learn
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 

Recently uploaded

Levelised Cost of Hydrogen (LCOH) Calculator Manual
Levelised Cost of Hydrogen  (LCOH) Calculator ManualLevelised Cost of Hydrogen  (LCOH) Calculator Manual
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Massimo Talia
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
MadhavJungKarki
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
openshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoinopenshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoin
snaprevwdev
 
Introduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.pptIntroduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.ppt
Dwarkadas J Sanghvi College of Engineering
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
OKORIE1
 
5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf
AlvianRamadhani5
 
Unit -II Spectroscopy - EC I B.Tech.pdf
Unit -II Spectroscopy - EC  I B.Tech.pdfUnit -II Spectroscopy - EC  I B.Tech.pdf
Unit -II Spectroscopy - EC I B.Tech.pdf
TeluguBadi
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...
um7474492
 
Bituminous road construction project based learning report
Bituminous road construction project based learning reportBituminous road construction project based learning report
Bituminous road construction project based learning report
CE19KaushlendraKumar
 
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICSUNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
vmspraneeth
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
uqyfuc
 
Supermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdfSupermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdf
Kamal Acharya
 
FULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back EndFULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back End
PreethaV16
 

Recently uploaded (20)

Levelised Cost of Hydrogen (LCOH) Calculator Manual
Levelised Cost of Hydrogen  (LCOH) Calculator ManualLevelised Cost of Hydrogen  (LCOH) Calculator Manual
Levelised Cost of Hydrogen (LCOH) Calculator Manual
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
openshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoinopenshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoin
 
Introduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.pptIntroduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.ppt
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
DESIGN AND MANUFACTURE OF CEILING BOARD USING SAWDUST AND WASTE CARTON MATERI...
 
5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf
 
Unit -II Spectroscopy - EC I B.Tech.pdf
Unit -II Spectroscopy - EC  I B.Tech.pdfUnit -II Spectroscopy - EC  I B.Tech.pdf
Unit -II Spectroscopy - EC I B.Tech.pdf
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...
 
Bituminous road construction project based learning report
Bituminous road construction project based learning reportBituminous road construction project based learning report
Bituminous road construction project based learning report
 
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICSUNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Supermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdfSupermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdf
 
FULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back EndFULL STACK PROGRAMMING - Both Front End and Back End
FULL STACK PROGRAMMING - Both Front End and Back End
 

Mockito junit

  • 1.
  • 8.
  • 10. private static final String USER = ”user123"; private static final String PASSWORD = ”pass123 @Test public void testLoginSucess(){ LoginController loginBean = new LoginController(); LoginResponse outcome = loginBean.login(USER,PASSWORD); Assert.assertEquals("Test Sucess login",true,outcome.isLoged()); } Write a test for your controller as clean and simple as possible it doesn't need pass or even compile
  • 11. • Problem: • Client have their own login service witch integration layer is not ready yet. • You need to invoke login integration layer to perform login. • Solution: • Create a login integration mock. • Inject login integration mock into loginController <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.15.0</version> <scope>test</scope> </dependency> authenticatorMock = mock(AuthenticatorInterface.class); loginBean.setAutenticator(authenticatorMock); when(authenticatorMock.login(USER,PASSWORD)).thenReturn(true);
  • 12. Given user perform login then audit login attempt verify(authenticatorMock,atLeastOnce()).audit(USER,"BEGIN"); Given user perform login when credentials are correct then audit login success verify(authenticatorMock,atLeastOnce()).audit(USER,"SUCESS")
  • 13. Check the execution order of your class, in real implementation even! InOrder inOrder = inOrder(authenticatorMock); inOrder.verify(authenticatorMock,atLeastOnce()).audit(USER,"BEGIN"); inOrder.verify(authenticatorMock,times(1)).login(USER,PASSWORD); inOrder.verify(authenticatorMock, atLeast(1)).audit(USER,"SUCESS");
  • 14. Given user perform login when credentials are correct then send mail notification verify(loginBean,times(1)).notifyEvent(USER,"SUCESS"); loginBean = spy(new LoginController());
  • 15. Given user perform login when credentials are not correct then return false Given user perform login when password is not valid then return IllegalArgumentException when(authenticatorMock.login(USER,null)) .thenThrow(new IllegalArgumentException()); Create an argument matcher and make more BDD like given(authenticatorMock.login(eq(USER), argThat(invallidPassword ))) .willThrow(new IllegalArgumentException()); private static ArgumentMatcher<String> invallidPassword = new ArgumentMatcher<String>() { public boolean matches(String s) { return //implement your argument validator; } };
  • 16. Given user perform login when credentials are correct then return login menu and last login date. Assert.assertEquals("verify user info size",2,outcome.getUserInfo().size()); private Answer sucessAnswer = new Answer<HashMap<String, Object>>() { public HashMap<String, Object> answer(InvocationOnMock invocationOnMock) throws Throwable { HashMap<String, Object> userInfo = new HashMap<String, Object>(); //create your custom answer return userInfo; } }; when(dataProviderMock.getUserInfo(USER)) .thenAnswer(sucessAnswer);
  • 17. Mockito PowerMock 2.8.0-2.8.9 1.7.x 2.7.5 1.7.0RC4 2.4.0 1.7.0RC2 1.10.8 - 1.10.x 1.6.2 - 2.0 1.9.5-rc1 - 1.9.5 1.5.0 - 1.5.6 1.8.5 1.3.9 - 1.4.9 1.8.4 1.3.7 & 1.3.8 1.8.3 1.3.6 1.8.1 & 1.8.2 1.3.5 1.8 1.3
  • 18. Private field? -> Whitebox.setInternalState(loginBean, "dataProvider", dataProviderMock); Static method? -> mockStatic(LoginController.class); @RunWith(PowerMockRunner.class) @PrepareForTest(LoginController.class) public class LoginControllerTest { } Avoid constructor -> Whitebox.newInstance(LoginController.class) Avois static inizializer -> @SuppressStaticInitializationFor("com.jug.mockito.LoginController") Avoid method -> suppress(method(LoginController.class, "notifyAllNodes"))

Editor's Notes

  1. Martin Fowler Dummy :parametros, menus , valores de entrada Fake: fake smtp, dbunit Stubs: carrito, servicios
  2. "You Aren't Gonna Need It". Martin Fowler
  3. Template:junitdep Template:loginTest
  4. Template:loginc1 Template:mockitodep Template:mockauthenticator1 Borrar instancia de login controller en la prueba, ahora esta en before
  5. Pasar de verify(authenticatorMock).audit(USER,"BEGIN"); -> verify(authenticatorMock,atLeastOnce()).audit(USER,"BEGIN"); Template:loginrefactor1 Luego jugar con el orden de auditoria se necesita verificar alg’un orden
  6. Template:loginTestInOrder
  7. Spy en set up Agregar en login controller cuando es login exitoso: this.notifyEvent(user,"SUCESS");
  8. Template:loginfail Probar login flase con badpassword y sin excepcion esperada luego pasar a excepcion Template:matcher
  9. Setear mock de data provider private DataProviderInterface dataProviderMock; Template:testmenu Tempkate:menu1 Template:menuanswer