SlideShare a Scribd company logo
1 of 21
unit testing on the rocks!
Why mock?
Isolation
Example

    AccountController
                          HellotxtManagement
+addAccount
+deleteAccount
                         ...
...
Example

    AccountController
                          HellotxtManagement
+addAccount
+deleteAccount
                         ...
...
The no-so-good way
                              HellotxtManagement

                             ...




    HellotxtManagementMock
 void addAccount(){
    //do what I want
 }
 ..
The no-so-good way
                              HellotxtManagement

                             ...




    HellotxtManagementMock              HellotxtManagementMock2
 void addAccount(){                  void addAccount(){
    //do what I want                    //now do this
 }                                   }
 ..                                  ..
The no-so-good way
                              HellotxtManagement

                             ...




    HellotxtManagementMock              HellotxtManagementMock2      HellotxtManagementMock3
 void addAccount(){                  void addAccount(){           void addAccount(){
    //do what I want                    //now do this                //throw exception
 }                                   }                            }
 ..                                  ..                           ..
The mockito way
Test Workflow
1. Create Mock
2. Stub
3. Invoke
4. Verify
5. Assert expectations
Creating a Mock

import static org.mockito.Mockito.*;


...
// You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
Stubbing

// stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
What’s going on?

// following prints "first"
System.out.println(mockedList.get(0));

// following throws runtime exception
System.out.println(mockedList.get(1));

// following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
Verify

// Although it is possible to verify a stubbed invocation, usually it's
// just redundant
// If your code cares what get(0) returns then something else breaks
// (often before even verify() gets executed).
// If your code doesn't care what get(0) returns then it should not be
// stubbed. Not convinced? See here.
verify(mockedList).get(0);
What about void
       methods?
• Often void methods you just verify them.
         //create my mock and inject it to my unit under test
         DB mockedDb = mock(DB.class);
         MyThing unitUnderTest = new MyThing(mockedDb);
         	   	
         //invoke what we want to test
         unitUnderTest.doSothing();
         	   	
         //verify we didn't forget to save my stuff.
         verify(mockedDb).save();
What about void
            methods?
• Although you can also Stub them to throw
     an exception.
 @Test(expected = HorribleException.class)
 public void test3() throws Exception {
 	   	   // create my mock and inject it to my unit under test
 	   	   Oracle oracleMock = mock(Oracle.class);
 	   	   MyThing unitUnderTest = new MyThing(oracleMock);

 	    	   String paradox = "This statement is false";

 	    	   // stub
 	    	   doThrow(new HorribleException()).when(oracleMock).thinkAbout(paradox);

 	    	   unitUnderTest.askTheOracle(paradox);
 }
Argument Matchers

when(hellotxtManagementMock.addAccount(Mockito.any(Session.class), Mockito.anyString(),
	   	   	   	   	   	   	   Mockito.anyMap(), Mockito.anyString())).thenReturn(account);
Custom Argument
                  Matcher
Mockito.when(hellotxtManagementMock.getAuthenticationInfo(Mockito.argThat(new IsValidSession()),
	   	   	   	   	   	   Mockito.eq(Networks.FACEBOOK))).thenReturn(expectedResult);



                                               ...
private   class IsValidSession extends ArgumentMatcher<Session> {
	   	     @Override
	   	     public boolean matches(Object argument) {
	   	     	   return argument instanceof Session
	   	     	   	   	   && ((Session) argument).getSessionId().equals(TestValues.VALID_SESSION_ID);
	   	     }
}
Argument Capture
    ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class);
                                          ...
   ModelAndView result = accountController.addAccount(json.toString(), sessionId, deviceType,
   deviceId, networkId);

                                          ...
verify(hellotxtManagementMock).addAccount(sessionCaptor.capture(), Mockito.eq(networkId),
	   	   	   	   	   Mockito.eq(parameters), Mockito.eq(redirectUrl));

                                          ...
    assertEquals(sessionId, sessionCaptor.getValue().getSessionId());
    assertEquals(deviceType, sessionCaptor.getValue().getDevice().getType().name());
    assertEquals(deviceId, sessionCaptor.getValue().getDevice().getUid());
Basic Unit Testing with Mockito

More Related Content

What's hot

JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etcYaron Karni
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with EasymockÜrgo Ringo
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 

What's hot (17)

Power mock
Power mockPower mock
Power mock
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Mockito
MockitoMockito
Mockito
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Android testing
Android testingAndroid testing
Android testing
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
JMockit
JMockitJMockit
JMockit
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
J query
J queryJ query
J query
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
Exception
ExceptionException
Exception
 

Viewers also liked

Programmer testing
Programmer testingProgrammer testing
Programmer testingJoao Pereira
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 

Viewers also liked (12)

Programmer testing
Programmer testingProgrammer testing
Programmer testing
 
Demystifying git
Demystifying git Demystifying git
Demystifying git
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
How to Use Slideshare
How to Use SlideshareHow to Use Slideshare
How to Use Slideshare
 

Similar to Basic Unit Testing with Mockito

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdfgauravavam
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in productionMartijn Dashorst
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irstjkumaranc
 
Csphtp1 11
Csphtp1 11Csphtp1 11
Csphtp1 11HUST
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutDror Helper
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design ExamplesTareq Hasan
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean testsDanylenko Max
 
IP project for class 12 cbse
IP project for class 12 cbseIP project for class 12 cbse
IP project for class 12 cbsesiddharthjha34
 

Similar to Basic Unit Testing with Mockito (20)

Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irst
 
Csphtp1 11
Csphtp1 11Csphtp1 11
Csphtp1 11
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Clean Code - A&BP CC
Clean Code - A&BP CCClean Code - A&BP CC
Clean Code - A&BP CC
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
IP project for class 12 cbse
IP project for class 12 cbseIP project for class 12 cbse
IP project for class 12 cbse
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Basic Unit Testing with Mockito

  • 1. unit testing on the rocks!
  • 4. Example AccountController HellotxtManagement +addAccount +deleteAccount ... ...
  • 5. Example AccountController HellotxtManagement +addAccount +deleteAccount ... ...
  • 6. The no-so-good way HellotxtManagement ... HellotxtManagementMock void addAccount(){ //do what I want } ..
  • 7. The no-so-good way HellotxtManagement ... HellotxtManagementMock HellotxtManagementMock2 void addAccount(){ void addAccount(){ //do what I want //now do this } } .. ..
  • 8. The no-so-good way HellotxtManagement ... HellotxtManagementMock HellotxtManagementMock2 HellotxtManagementMock3 void addAccount(){ void addAccount(){ void addAccount(){ //do what I want //now do this //throw exception } } } .. .. ..
  • 9.
  • 11. Test Workflow 1. Create Mock 2. Stub 3. Invoke 4. Verify 5. Assert expectations
  • 12. Creating a Mock import static org.mockito.Mockito.*; ... // You can mock concrete classes, not only interfaces LinkedList mockedList = mock(LinkedList.class);
  • 14. What’s going on? // following prints "first" System.out.println(mockedList.get(0)); // following throws runtime exception System.out.println(mockedList.get(1)); // following prints "null" because get(999) was not stubbed System.out.println(mockedList.get(999));
  • 15. Verify // Although it is possible to verify a stubbed invocation, usually it's // just redundant // If your code cares what get(0) returns then something else breaks // (often before even verify() gets executed). // If your code doesn't care what get(0) returns then it should not be // stubbed. Not convinced? See here. verify(mockedList).get(0);
  • 16. What about void methods? • Often void methods you just verify them. //create my mock and inject it to my unit under test DB mockedDb = mock(DB.class); MyThing unitUnderTest = new MyThing(mockedDb); //invoke what we want to test unitUnderTest.doSothing(); //verify we didn't forget to save my stuff. verify(mockedDb).save();
  • 17. What about void methods? • Although you can also Stub them to throw an exception. @Test(expected = HorribleException.class) public void test3() throws Exception { // create my mock and inject it to my unit under test Oracle oracleMock = mock(Oracle.class); MyThing unitUnderTest = new MyThing(oracleMock); String paradox = "This statement is false"; // stub doThrow(new HorribleException()).when(oracleMock).thinkAbout(paradox); unitUnderTest.askTheOracle(paradox); }
  • 19. Custom Argument Matcher Mockito.when(hellotxtManagementMock.getAuthenticationInfo(Mockito.argThat(new IsValidSession()), Mockito.eq(Networks.FACEBOOK))).thenReturn(expectedResult); ... private class IsValidSession extends ArgumentMatcher<Session> { @Override public boolean matches(Object argument) { return argument instanceof Session && ((Session) argument).getSessionId().equals(TestValues.VALID_SESSION_ID); } }
  • 20. Argument Capture ArgumentCaptor<Session> sessionCaptor = ArgumentCaptor.forClass(Session.class); ... ModelAndView result = accountController.addAccount(json.toString(), sessionId, deviceType, deviceId, networkId); ... verify(hellotxtManagementMock).addAccount(sessionCaptor.capture(), Mockito.eq(networkId), Mockito.eq(parameters), Mockito.eq(redirectUrl)); ... assertEquals(sessionId, sessionCaptor.getValue().getSessionId()); assertEquals(deviceType, sessionCaptor.getValue().getDevice().getType().name()); assertEquals(deviceId, sessionCaptor.getValue().getDevice().getUid());

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n