Behavior test with mockito

java

behavior test

Behavior test is to test the behavior of a method, that is whether the method is invoked with expected parameters for expected number of times. Whereas, state test is to verify that a method yields expected result with specific input arguments. I prefer state test because behavior test focuses on validating the execution steps which are easy to change over time.

I tend to adopt behavior test when a method is void. A void method must have some side effects otherwise the method is nothing useful. It's far from the scope of the test method if we try to validate the outer state the void method updates. See below example:

import static org.mockito.Mockito.times;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

  @Mock
  private UserRepository repo;

  @InjectMocks
  private UserService service;

  @Test
  public void testUserInsert() {
    User user = new User();
    service.insert(user);
    // behavior test
    Mockito.verify(repo, times(1)).save(user);
    Mockito.verifyNoMoreInteractions(repo);
  }
}

class User {

}

class UserRepository {

  void save(User user) {

  }
}

class UserService {

  private final UserRepository repo;

  UserService(UserRepository repo) {
    this.repo = repo;
  }

  public void insert(User user) {
    repo.save(user);
  }
}