我想测试一个Spring boot 2 respository作为rest控制器应用程序。App在浏览器( http://localhost:8080/api/v1/ehdata )上工作得很好,但我找不到一个示例,我如何在Spring测试环境中测试它。非常重要的是,没有RestControllers和服务,只有这样注释的存储库:
@RepositoryRestResource(path = EhDataRepository.BASE_PATH,
collectionResourceRel = EhDataRepository.BASE_PATH)
public interface EhDataRepository extends
PagingAndSortingRepository<EhData, Long> {
public static final String BASE_PATH="ehdata";
}我尝试了此测试,但响应为空,状态代码为404:
@RunWith(SpringRunner.class)
@SpringBootTest
@WebMvcTest(EhDataRepository.class)
public class RestTest extends AbstractRestTest {
@Autowired MockMvc mvc;
@Test
public void testData() throws Exception {
mvc.perform(get("/api/v1/ehdata")
.accept(MediaTypes.HAL_JSON_VALUE))
.andDo(print())
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CONTENT_TYPE,
MediaTypes.HAL_JSON_VALUE+";charset=UTF-8")
.andReturn();
}
}thx,Zamek
发布于 2019-03-20 18:33:27
您将需要根据您尝试测试的方法来模拟存储库的输出,如下所示:
@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时,请删除server-context-path。
https://stackoverflow.com/questions/54907668
复制相似问题