Spring boot 测试Spring数据Rest

Spring boot 测试Spring数据Rest,spring-boot,spring-data-rest,Spring Boot,Spring Data Rest,我想测试一个Spring boot 2 respository作为rest控制器应用程序。 这个应用程序在browser()上运行良好,但我找不到一个示例,说明如何使用Spring测试环境对其进行测试。非常重要的是,没有RESTController和服务,只有注释如下的存储库: @RepositoryRestResource(path = EhDataRepository.BASE_PATH, collectionResourceRel = Eh

我想测试一个Spring boot 2 respository作为rest控制器应用程序。 这个应用程序在browser()上运行良好,但我找不到一个示例,说明如何使用Spring测试环境对其进行测试。非常重要的是,没有RESTController和服务,只有注释如下的存储库:

@RepositoryRestResource(path = EhDataRepository.BASE_PATH, 
                        collectionResourceRel = EhDataRepository.BASE_PATH)
public interface EhDataRepository extends 
PagingAndSortingRepository<EhData, Long> {

    public static final String BASE_PATH="ehdata";
}
thx,
Zamek

您需要根据您尝试测试的方法模拟respository的输出,如下所示:

 @MockBean
 private ProductRepo repo;
然后

Mockito.when(this.repo.findById("PR-123")
    .get())
    .thenReturn(this.product);
this.mvc.perform(MockMvcRequestBuilders.get("/products/{id}", "PR-123")
    .contentType(MediaType.APPLICATION_JSON_VALUE))
    .andReturn();
另外,在perform()方法中调用API时删除服务器上下文路径

Mockito.when(this.repo.findById("PR-123")
    .get())
    .thenReturn(this.product);
this.mvc.perform(MockMvcRequestBuilders.get("/products/{id}", "PR-123")
    .contentType(MediaType.APPLICATION_JSON_VALUE))
    .andReturn();