测试Spring Data Rest

问题描述 投票:0回答:1

我想测试Spring boot 2存储库作为其他控制器应用程序。应用程序从浏览器(http://localhost:8080/api/v1/ehdata)运行良好,但我找不到一个示例如何使用Spring测试环境进行测试。非常重要的是,没有RestControllers和Services,只有这样的Repositories注释:

@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,城堡

spring-boot spring-data-rest
1个回答
1
投票

您将需要根据您尝试测试的方法模拟存储库中的输出:

 @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。

© www.soinside.com 2019 - 2024. All rights reserved.