N.B. This post has been reposted for educational purpose only, there is no intention for 
infringement of copyright issues(if there any). And conveys proper acknowledgement to the
author. Posted By: Baljit Garcha
Mockito is an open source mocking framework for unit testing code in Java. Mockito allows the creation of Mock objects (simulated objects that mimic the behavior of real objects) for use in automated unit testing in conjunction with frameworks like Junit.

Maven Dependency

<dependency>
    <groupid>org.mockito</groupid>
    <artifactid>mockito-all</artifactid>
    <version>1.9.5</version>
</dependency>

Test Subject (classes to test)

package com.blog.cavalr;
 
import java.util.Date;
 
public class UserManager {
    private UserService userService;
 
    public void saveUser(User user) {
        userService.saveUser(user);
    }
 
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
 
    public User findUser(String userName) {
        return userService.findUserByName(userName);
    }
 
    public Date getUserLastLogin(User user) {
        return user.getLoginDate();
    }
 
    public void updateUser(String user, Date lastLoginDate) {
        userService.updateUser(user, lastLoginDate);
    }
}

UserManager, an SUT (System Under Test) has APIs like saveUsergetUserLastLogin and updateUserUserManager relies in service UserService to perform save, update etc. So while unit testing UserManager, we will mock the UserService and inject into UserManager.

package com.blog.cavalr;
 
import java.util.Date;
 
public class UserService {
 
    public void saveUser(User user) {
        //Save user
        System.out.println("Saving user " + user);
    }
 
    public User findUserByName(String userName) {
        return new User(userName);
    }
 
    public void updateUser(String user, Date lastLoginDate) {
        //Update user
        System.out.println("Update user " + user);
    }
}

package com.blog.cavalr;
 
import java.util.Date;
 
public class User {
 
    private String userName;
 
    private Date loginDate;
 
    public User(String userName) {
        this.userName = userName;
    }
 
    public User(String userName, Date loginDate) {
        this.userName = userName;
        this.loginDate = loginDate;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public Date getLoginDate() {
        return loginDate;
    }
 
    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }
}

…and it all starts here

Create your first mock with Mockito!

Mock UserService class first and then inject it into UserManager.

@Before
public void setUp() throws Exception {
    userService = Mockito.mock(UserService.class);
    userManager = new UserManager();
    userManager.setUserService(userService);
}

Same can achieved with annotations from Mockito framework.

@RunWith(MockitoJUnitRunner.class)
public class AnnotationMockTest {
 
    @InjectMocks
    private UserManager userManager;
 
    @Mock
    private UserService userService;
}

Verify Behavior

Let’s verify if call was made to the mock service

   @Test
    public void testSaveUser() throws Exception {
        User user = new User("u1");
        userManager.saveUser(user);
 
        //Verify if saveUser was invoked on userService with given 'user' object.
        Mockito.verify(userService).saveUser(user);
 
        //Verify with Argument Matcher
        Mockito.verify(userService).saveUser(Mockito.<user>any());
    }
</user>

Check the number of Interactions

@Test
public void testCountNumberOfInteractions() throws Exception {
 
    userManager.findUser("user1");
 
    //Verify the number of interactions with mock
    Mockito.verify(userService, Mockito.times(1)).findUserByName("user1");
 
    //There was only one interaction with userService
    Mockito.verifyNoMoreInteractions(userService);
}

Zero Interactions with Mock

@Test
public void testZeroInteractionsWithMock() throws Exception {
 
    User user = new User("user1", new Date());
 
    //call method where no call to userService will be made
    userManager.getUserLastLogin(user);
    Mockito.verifyZeroInteractions(userService);
 
    //Another way to check zero interactions
    userManager.getUserLastLogin(user);
    Mockito.verify(userService, Mockito.never());
}

Lets do some stubbing

@Test
public void testFindUser() throws Exception {
 
    //Stub the value that will returned on call to userService.findUserByName
    User stubbedUser = new User("userAfterSave");
    Mockito.when(userService.findUserByName("user1")).thenReturn(stubbedUser);
 
    //make the call
    User user = userManager.findUser("user1");
 
    //Verify if findUserByName method was invoked on userService call
    Mockito.verify(userService).findUserByName("user1");
 
    Assert.assertEquals("userAfterSave", user.getUserName());
}

Stub an ArrayList

@Test
public void testStubArrayList() throws Exception {
 
    //Mock the Arraylist
    ArrayList mock = Mockito.mock(ArrayList.class);
 
    //Stub the values
    Mockito.when(mock.get(0)).thenReturn("value1");
    Mockito.when(mock.get(1)).thenReturn("value2");
 
    //Check the value at 0 & 1
    Assert.assertEquals("value1", mock.get(0));
    Assert.assertEquals("value2", mock.get(1));
 
}

Stub the call and then custom answer

    @Test
    public void testStubAndAnswer() throws Exception {
 
        //when method is invoked on mock, do some processing before return the stubbed object
 
        Mockito.when(userService.findUserByName(Mockito.anyString())).then(new Answer<user>() {
 
            public User answer(InvocationOnMock invocation) throws Throwable {
 
                //check argument passed to method if its not null
                //then give me time of day and make me a coffee before you return
                //you get the point, you can do anything here before returning
 
                Assert.assertNotNull(invocation.getArguments()[0]);
 
                return new User("UserCreatedByCallback");
            }
        });
 
        User user = userManager.findUser("user1");
 
        Assert.assertEquals("UserCreatedByCallback", user.getUserName());
 
 
        //Another way of answering the call
        Mockito.doAnswer(new Answer() {
 
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
 
                return new User("UserCreatedByCallback");
 
            }
 
        }).when(userService).findUserByName(Mockito.anyString());
 
    }
</user>

Argument Matcher

    @Test
    public void testArgumentMatcher() throws Exception {
 
        Mockito.when(userService.findUserByName(Mockito.<string>any())).thenReturn(Mockito.<user>any());
 
        userManager.findUser("user");
 
        //Verify if saveUser was invoked on userService with given 'user' object.
        Mockito.verify(userService).findUserByName("user");
 
        //Another example
        userManager.updateUser("user", new Date());
 
        Mockito.verify(userService).updateUser(Mockito.eq("user"), Mockito.<date>any());
    }
</date></user></string>

Throw Exception

@Test(expected = RuntimeException.class)
public void testThrowException() throws Exception {
 
    //throw an exception on call to userService
    Mockito.doThrow(new RuntimeException()).when(userService).saveUser(Mockito.<User>any());
 
    //this will throw RunTime exception
    userManager.saveUser(Mockito.mock(User.class));
 
}