【问题标题】:how to test the CRUD service which only invoke the repository (dao) layer?如何测试仅调用存储库(dao)层的 CRUD 服务?
【发布时间】:2017-10-12 11:39:02
【问题描述】:

例如,我们有一个简单调用 JpaRepository 方法的服务层。平常的渣滓

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

如何正确测试这些方法?

只是服务调用了dao层?

@Mock
private UserRepository userRepository;

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

更新:

好的,findAll() 是一个简单的例子,当我们使用

when(userRepository.findAll()).thenReturn(usersList);

我们实际上只是在做一个测试覆盖,测试显而易见的东西。

还有一个问题。

我们是否需要测试此类服务 сrud 方法?

只调用dao层的方法

【问题讨论】:

  • 您想在不访问数据库的情况下测试您的服务层,还是想在连接到数据库的情况下测试存储库层?
  • 没有数据库,使用模拟

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我的做法是

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

    【讨论】:

      猜你喜欢
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 2012-03-19
      • 1970-01-01
      相关资源
      最近更新 更多