how to test the CRUD service which only invoke the

2019-05-06 14:46发布

问题:

for example, we have a layer of service that simple invoke the JpaRepository method. usual crud

public List<User> findAll() {
    return userRepository.findAll();
}

how to correctly test such methods?

just that the service invokes the dao layer?

@Mock
private UserRepository userRepository;

@Test
public void TestfindAllInvokeUserServiceMethod(){
            userService.findAll();
            verify(userRepository.findAll());
}

upd:

ok, findAll() is simple example, when we using

when(userRepository.findAll()).thenReturn(usersList);

we are actually doing only a test coverage, testing the obvious things.

and a question.

do we need to test such service сrud methods?

which only invoke the methods of dao layer

回答1:

While you mock the repository, then you can do something like this:

List<User> users = Collections.singletonList(new User()); // or you can add more
when(userRepository.findAll()).thenReturn(users);

List<User> usersResult = userService.findAll();

assertThat(usersResult).isEqualTo(users); // AssertJ api


回答2:

The way I do it is

class UserRepository {
  public List<User> findAll(){
    /*
    connection with DB to find and return all users.
    */
  }
} 

class UserService {
  private UserRepository userRepository;

  public UserService(UserRepository userRepository){
    this.userRepository = userRepository;
  }

  public List<User> findAll(){
    return this.userRepository.findAll();
  }
}   

class UserServiceTests {
    /* Mock the Repository */
    private UserRepository userRepository = mock(UserRepository.class);
    /* Provide the mock to the Service you want to test */
    private UserService userService = new UserService(userRepository);
    private User user = new User();

    @Test
    public void TestfindAllInvokeUserServiceMethod(){
      /* this will replace the real call of the repository with a return of your own list created in this test */
      when(userRepository.findAll()).thenReturn(Arrays.asList(user));
      /* Call the service method */
      List<User> users = userService.findAll();

      /*
      Now you can do some Assertions on the users
      */
    }
}