how to test the CRUD service which only invoke the repository (dao) layer?

爷,独闯天下 提交于 2019-12-05 14:29:47

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
      */
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!