[英]how to test the CRUD service which only invoke the repository (dao) layer?
for example, we have a layer of service that simple invoke the JpaRepository method. 例如,我们有一层简单地调用JpaRepository方法的服务。 usual crud 通常的粗鲁
public List<User> findAll() {
return userRepository.findAll();
}
how to correctly test such methods? 如何正确测试这样的方法?
just that the service invokes the dao layer? 只是该服务调用dao层?
@Mock
private UserRepository userRepository;
@Test
public void TestfindAllInvokeUserServiceMethod(){
userService.findAll();
verify(userRepository.findAll());
}
upd: UPD:
ok, findAll() is simple example, when we using 好的,findAll()是一个简单的例子,当我们使用时
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? 我们需要测试这样的服务сrud方法吗?
which only invoke the methods of dao layer 它只调用dao层的方法
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
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
*/
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.