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

Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
Ürgo Ringo
 
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
EndranNL
 

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

Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
suhasreddy1
 

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

Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
Martijn 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 & STM
Mario Fusco
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irst
jkumaranc
 
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
Tomek Kaczanowski
 

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

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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