Assume you want to create a unit test for UserService class, getUserByUserName(String username) method.

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    public User getUserByUserName(String username) {

Create new class name UserServiceImplTest

public class UserServiceImplTest {

Inject class you want to test

private UserServiceImpl userService;

private UserDao userDaoMock;

Setup annotation support

public void setup() {

Create test method

public void shoudXXX() {

Verify expectation

assertThat(true, equalTo(true));

Static import required classes

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

Method Template

public void should<Expecting>When<Criteria>On<MehtodName> {
    // Given
    Declare your mock object and expectation.
    // When
    Invoke method you want to test.
    // Then
    Verify method invocation.
    Check return value from the method.


public void shouldReturnUserWhenUserNameIsNotNullOnGetUserByUserName {
    // Given
    User userMock = mock(User.class);
    // When
    User returnUser = userService.getUserByUserName("admin");
    // Then
    assertThat(returnUser, equalTo(userMock));