x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Mockito Junit Tutorial

    Mockito is an open source unit test framework in Java used for mocking. Using Mockito framework you can set the expection what an object will return, or what exception it throws or count how may times it was invoked.

    1. Integrate Mockito and JUnit using MockitoJUnitRunner.

    In this example, we will mock DAO interface that is used by Service class using Mockito framework.

    Step 1) Add mockito-core dependency to maven file

    Maven details

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.3.3</version>
        <scope>test</scope>
    </dependency>

    Gradle details

    dependencies { testCompile 'org.mockito:mockito-core:3.3.3' }   

    Step 2) Write a UserDAO interface, UserService class

    Note that we will not implement UserDAO interface, rather will mock it (using Mockito @Mock ) when it is called in UserService class.

    package dao;
    
    public interface UserDAO {
    	
        public String getUserName(String id);
    
    }	
    package service;
    
    import dao.UserDAO;
    
    public class UserService {
    	
        private UserDAO userDAO;
    	
        public void setUserDAO(UserDAO userDAO) {
            this.userDAO = userDAO;
        }
    
        public String getUserName(String id) {
            return userDAO.getUserName(id);
        }
    
    }

    Step 3) Write JUnit UserServiceTest class which tests getUserName() method of UserService Class

    To mock a class using Mockito, you can either use Mockito mock() method or use @Mock annotation. If you use Mockito mock() method, you have to set the mock reference in the class to be tested. But if you use @Mock annotation, then you can use @InjectMocks annotation to automatically set the mock object in test class and also you have to use MockitoAnnotations.initMock(this) or use MockitoJUnitRunner.

    Note that UserDAO implementation is not used, rather it is mocked when it is called in UserService class.

    Mock using Mockito mock()

    package service;
    
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.doNothing;
    import static org.mockito.Mockito.when;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.mockito.ArgumentCaptor;
    import org.mockito.Mockito;
    
    public class UserServiceTest {
    	
        private UserService userService = new UserService();
         
        private UserDAO userDAO;
        
       @Before
        public void setUp() {
        	userDAO = Mockito.mock(UserDAO.class);
        	userService.setUserDAO(userDAO);
        }
    
        @Test
        public void testGetUserName() {
            when(userDAO.getUserName("u768034")).thenReturn("John Bocelli");
            String userName = userService.getUserName("u768034");
            assertNotNull(userName);
        }
    
    }	

    Mock using @Mock annotation

    package service;
    
    import static org.junit.Assert.assertNotNull;
    import static org.mockito.Mockito.when;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.junit.MockitoJUnitRunner;
    
    import dao.UserDAO;
    
    @RunWith(MockitoJUnitRunner.class)
    public class UserServiceTest {
    	
        @InjectMocks
        private UserService userService = new UserService();
         
        @Mock
        private UserDAO userDAO;
    
        @Test
        public void testGetUserName() {
            when(userDAO.getUserName("u768034")).thenReturn("John Bocelli");
            String userName = userService.getUserName("u768034");
            assertNotNull(userName);
        }
    
    }	

    2. Mock void method using Mockito doNothing()

    Sometimes we have to mock calls which have return type as void. These calls can be mocked using Mockito doNothing(). In this example, we will mock DAO interface method that does not return any value and is called by Service class using Mockito doNothing()

    Step 1) Write a UserDAO interface, UserService class

    Note that we will not implement UserDAO interface, rather will mock it (using Mockito @Mock ) when it is called in UserService class.

    package dao;
    
    public interface UserDAO {
    	
        public void updateUserName(String id, String name);
    
    }	
    package service;
    
    import dao.UserDAO;
    
    public class UserService {
    	
        private UserDAO userDAO;
    	
        public void setUserDAO(UserDAO userDAO) {
            this.userDAO = userDAO;
        }
       
        public void updateUserName(String id, String name) {
            userDAO.updateUserName(id, name);
        }
    
    }

    Step 2) Write JUnit UserServiceTest class which tests updateUserName() method of UserService Class

    Note that since updateUserName() method return type is void, we need to use Mockito doNothing() to mock the void method.

    package service;
    
    import static org.junit.Assert.assertNotNull;
    import static org.mockito.Mockito.when;
    import static org.mockito.Mockito.doNothing;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.junit.MockitoJUnitRunner;
    
    import dao.UserDAO;
    
    @RunWith(MockitoJUnitRunner.class)
    public class UserServiceTest {
    	
        @InjectMocks
        private UserService userService = new UserService();
         
        @Mock
        private UserDAO userDAO;
    
        @Test
        public void testUpdateUserName() {
            doNothing().when(userDAO).updateUserName("u768034", "John");
            userService.updateUserName("u768034", "John");
        }
    
    }	

    3. Verify method invocation on a mock object

    To verify if a method of mock object was invoked or how many times it was invoked, you can use verify(). Following method are used with verify() method to verify method calls:

    • times(int numberOfInvocations) will verify if a method was invoked specific number of times.
    • never() will verify if method was never invoked.
    • atLeastOnce() will verify if method was invoked at least once.
    • atMost(int numberOfInvocations) will verify if method was not invoked more than specified times.
    • only()will verify if only this method was invoked.

    package service;
    
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;
    import static org.mockito.Mockito.times;
    import static org.mockito.Mockito.verify;
    import static org.mockito.Mockito.when;
    import static org.mockito.Mockito.never;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.ArgumentCaptor;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.junit.MockitoJUnitRunner;
    
    import dao.UserDAO;
    
    @RunWith(MockitoJUnitRunner.class)
    public class UserServiceTest {
    	
        @InjectMocks
        private UserService userService = new UserService();
         
        @Mock
        private UserDAO userDAO;
    
        @Test
        public void testGetUserName() {
            when(userDAO.getUserName("u768034")).thenReturn("John Bocelli");
            String userName = userService.getUserName("u768034");
            assertNotNull(userName);
            verify(userDAO, times(1)).getUserName("u768034");
            verify(userDAO, never()).updateUserName("u768034" , "John");
        }
    
    }	

    4. Throwing exception using Mockito

    Sometimes you need to verify failure conditions also using JUnit. For example what if the method call throws exception and you want to verify that correct exception is thrown. In this case you can use Mockito's doThrow() and thenThrow() APIs. In case the mocked method has return type of void then you need to use doThrow() else you have to use thenThrow().

    package service;
    
    import static org.mockito.Mockito.doThrow;
    import static org.mockito.Mockito.when;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.junit.MockitoJUnitRunner;
    
    import dao.UserDAO;
    
    @RunWith(MockitoJUnitRunner.class)
    public class UserServiceTestException {
    	
        @InjectMocks
        private UserService userService = new UserService();
         
        @Mock
        private UserDAO userDAO;
    
        @Test(expected = IllegalArgumentException.class)
        public void testGetUserNameThrowsException() {
            when(userDAO.getUserName("")).thenThrow(new IllegalArgumentException("userid is empty"));
            userService.getUserName("");
        }
    
        @Test(expected = IllegalArgumentException.class)
        public void testUpdateUserNameThrowsException() {
            doThrow(new IllegalArgumentException("username is empty")).when(userDAO).updateUserName("u768034", "");
            userService.updateUserName("u768034", "");
        }
    
    }	


    References :

    Mockito doNothing()

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This