我试图在我的代码上运行一些集成测试,我使用来自spring-boot-test的一个spring-boot-test来设置预期的请求。
我有一个调用在运行我的测试时被多次调用,但它似乎在测试期间不持久。我的测试看起来如下:
@Test
void getHealthStatus() {
try {
RequestBuilder request = get("/actuator/hc").contentType("application/json");
MockServerBinder.bindPersistentThingworxPropertiesCall(
mockServer,
requestTo(new URI(String.format("%sProperties/TestProp", thingworxUrl))),
objectMapper.writeValueAsString(new PingResponse(DashboardIndicator.HEALTHY, 200))
);
DashboardStatusModel expectedResult = new DashboardStatusModel();
expectedResult.addResult("spring",service.getAppHealth());
expectedResult.addResult("thingworx", service.getThingworxAvailability());
assertOpenUrl(request);
MvcResult result = mockMvc.perform(get("/actuator/hc").contentType("application/json"))
.andExpect(status().isOk())
.andReturn();
DashboardStatusModel actualResult = objectMapper.readValue(result.getResponse().getContentAsString(), DashboardStatusModel.class);
assertEquals(expectedResult.getResults().get("spring"), actualResult.getResults().get("spring"));
assertEquals(expectedResult.getResults().get("thingworx").getStatus(),actualResult.getResults().get("thingworx").getStatus());
assertEquals(expectedResult.getResults().get("thingworx").getData().get("url"), actualResult.getResults().get("thingworx").getData().get("url"));
} catch (Exception e) {
fail("Unable to perform REST call on GDP-API", e);
}
}作为补充资料:
mockServer是在这样的超类中创建的:protected static MockRestServiceServer mockServer;
@BeforeEach
public void configureMockServer() {
mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
}MockServerBinder.bindPersistentThingworxPropertiesCall()是一个类似于下面的帮助类:public static void bindPersistentThingworxPropertiesCall(MockRestServiceServer mockServer, RequestMatcher request, String responseJSONasString){
mockServer.expect(ExpectedCount.once(), request)
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(responseJSONasString));
}assertOpenUrl(request);是一个函数,它通过使用MockMVC__:来检查URL是否没有任何身份验证
public void assertOpenUrl(RequestBuilder request){
try{
mockMvc.perform(request).andExpect(status().isOk());
} catch (Exception e) {
fail("Unable to perform REST call on GDP-API", e);
}
}当我运行这个测试时,expectedResult.addResult("thingworx", service.getThingworxAvailability());将能够使用MockRestServiceServer,但是assertOpenUrl(request);行将失败,因为MockRestServiceServer不再期待对在MockServerBinder.bindPersistantThingworxPropertyCall()中绑定的端点的调用。如果我在现有的MockServerBinder.bindPersistantThingworxPropertyCall()下复制和粘贴,则不会发生这种情况,所以我认为首先需要解决的问题是如何绑定请求。
据我所知,ExpectedCount.manyTimes()应该在测试期间保留此请求。这不是真的吗?还是有其他方法来绑定我的请求,使它在整个测试过程中仍然可用?
发布于 2022-09-23 10:10:35
PEBCAK问题。
正如您在bindPersistentThingworxPropertiesCall()中所看到的,实际上并没有使用ExpectedCount.manyTimes()。我没听清楚。改变了它现在起作用了。
https://stackoverflow.com/questions/73825794
复制相似问题