SlideShare a Scribd company logo
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
 }                                   }                            }
 ..                                  ..                           ..
Basic Unit Testing with Mockito
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 (17)

PPTX
Power mock
Piyush Mittal
 
PPTX
Mocking with Mockito
Paul Churchward
 
PPTX
Mockito
sudha rajamanickam
 
PPT
JMockit Framework Overview
Mario Peshev
 
PPTX
Junit, mockito, etc
Yaron Karni
 
PDF
All about unit testing using (power) mock
Pranalee Rokde
 
ODP
Easymock Tutorial
Sbin m
 
ODP
Unit testing with Easymock
Ürgo Ringo
 
PPT
EasyMock for Java
Deepak Singhvi
 
PDF
Android testing
Sean Tsai
 
PPTX
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
PPT
JMockit
Angad Rajput
 
PPTX
Easy mockppt
subha chandra
 
PPTX
J query
Ramakrishna kapa
 
PPT
Exception Handling
Sunil OS
 
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
Denilson Nastacio
 
PPT
Exception
Harry Potter
 
Power mock
Piyush Mittal
 
Mocking with Mockito
Paul Churchward
 
JMockit Framework Overview
Mario Peshev
 
Junit, mockito, etc
Yaron Karni
 
All about unit testing using (power) mock
Pranalee Rokde
 
Easymock Tutorial
Sbin m
 
Unit testing with Easymock
Ürgo Ringo
 
EasyMock for Java
Deepak Singhvi
 
Android testing
Sean Tsai
 
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
JMockit
Angad Rajput
 
Easy mockppt
subha chandra
 
Exception Handling
Sunil OS
 
Mastering Mock Objects - Advanced Unit Testing for Java
Denilson Nastacio
 
Exception
Harry Potter
 

Viewers also liked (12)

PDF
Programmer testing
Joao Pereira
 
PPTX
Demystifying git
Andrey Dyblenko
 
PDF
Software Engineering - RS3
AtakanAral
 
PPTX
Java Unit Testing
Nayanda Haberty
 
PDF
Clean Unit Test Patterns
Frank Appel
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PPTX
Understanding Unit Testing
ikhwanhayat
 
PDF
Unit testing best practices
nickokiss
 
PDF
Unit and integration Testing
David Berliner
 
PPTX
Unit Testing Concepts and Best Practices
Derek Smith
 
PPTX
UNIT TESTING PPT
suhasreddy1
 
ODP
How to Use Slideshare
Converting Copy
 
Programmer testing
Joao Pereira
 
Demystifying git
Andrey Dyblenko
 
Software Engineering - RS3
AtakanAral
 
Java Unit Testing
Nayanda Haberty
 
Clean Unit Test Patterns
Frank Appel
 
JUnit & Mockito, first steps
Renato Primavera
 
Understanding Unit Testing
ikhwanhayat
 
Unit testing best practices
nickokiss
 
Unit and integration Testing
David Berliner
 
Unit Testing Concepts and Best Practices
Derek Smith
 
UNIT TESTING PPT
suhasreddy1
 
How to Use Slideshare
Converting Copy
 
Ad

Similar to Basic Unit Testing with Mockito (20)

DOCX
Rhino Mocks
Anand Kumar Rajana
 
PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PDF
31b - JUnit and Mockito.pdf
gauravavam
 
PDF
JavaScript Refactoring
Krzysztof Szafranek
 
PDF
Keep your Wicket application in production
Martijn Dashorst
 
PPTX
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
PPT
Exceptions irst
jkumaranc
 
PPT
Csphtp1 11
HUST
 
PPTX
Introduction to aop
Dror Helper
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PDF
Fun Teaching MongoDB New Tricks
MongoDB
 
PPTX
The secret unit testing tools no one ever told you about
Dror Helper
 
PPTX
Ensure code quality with vs2012
Sandeep Joshi
 
PPTX
Imagine a world without mocks
kenbot
 
PPTX
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
solit
 
PPTX
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
PPTX
Clean Code - A&BP CC
JWORKS powered by Ordina
 
PPT
Java: Class Design Examples
Tareq Hasan
 
PDF
How to write clean tests
Danylenko Max
 
PDF
IP project for class 12 cbse
siddharthjha34
 
Rhino Mocks
Anand Kumar Rajana
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
31b - JUnit and Mockito.pdf
gauravavam
 
JavaScript Refactoring
Krzysztof Szafranek
 
Keep your Wicket application in production
Martijn Dashorst
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Exceptions irst
jkumaranc
 
Csphtp1 11
HUST
 
Introduction to aop
Dror Helper
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Fun Teaching MongoDB New Tricks
MongoDB
 
The secret unit testing tools no one ever told you about
Dror Helper
 
Ensure code quality with vs2012
Sandeep Joshi
 
Imagine a world without mocks
kenbot
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
solit
 
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
Clean Code - A&BP CC
JWORKS powered by Ordina
 
Java: Class Design Examples
Tareq Hasan
 
How to write clean tests
Danylenko Max
 
IP project for class 12 cbse
siddharthjha34
 
Ad

Recently uploaded (20)

PDF
July Patch Tuesday
Ivanti
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
July Patch Tuesday
Ivanti
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

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 } } } .. .. ..
  • 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