如何测试只调用存储库(dao)层的CRUD服务?

时间:2017-10-12 11:39:03

标签: java spring hibernate unit-testing integration-testing

例如,我们有一层服务,可以简单地调用JpaRepository方法。通常的crud

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

如何正确测试此类方法?

只是服务调用dao层?

@Mock
private UserRepository userRepository;

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

upd:

好的,当我们使用

时,findAll()就是一个简单的例子
when(userRepository.findAll()).thenReturn(usersList);

我们实际上只进行测试覆盖,测试显而易见的事情。

和一个问题。

我们需要测试这样的服务сrud方法吗?

只调用dao layer的方法

2 个答案:

答案 0 :(得分:3)

在模拟存储库时,您可以执行以下操作:

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

答案 1 :(得分:1)

我的方式是

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
      */
    }
}