如何测试只调用存储库(dao)层的CRUD服务? [英] how to test the CRUD service which only invoke the repository (dao) layer?
本文介绍了如何测试只调用存储库(dao)层的CRUD服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public List< User> findAll(){
return userRepository.findAll();
}
如何正确测试此类方法? p>
只是服务调用dao层?
@Mock
private UserRepository userRepository;
@Test
public void TestfindAllInvokeUserServiceMethod(){
userService.findAll();
verify(userRepository.findAll());
upd:
ok,findAll()就是一个简单的例子,当我们使用
when(userRepository.findAll ))thenReturn(usersList)。
我们实际上只在测试覆盖范围内测试显而易见的东西。
和一个问题。
我们需要测试这种服务吗? >
其中只调用dao层的方法
解决方案
while你可以模拟仓库,然后你可以做这样的事情:
List< User> users = Collections.singletonList(new User()); //或者当(userRepository.findAll()),然后返回(用户)时,你可以添加更多
;
列表<用户> usersResult = userService.findAll();
assertThat(usersResult).isEqualTo(users); // AssertJ api
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
解决方案
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
这篇关于如何测试只调用存储库(dao)层的CRUD服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文