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的方法
答案 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
*/
}
}