【发布时间】:2021-11-12 01:39:03
【问题描述】:
@DisplayName("test getCarportById(), Status OK")
@Test
void testGetCarportLocationById() throws Exception {
// given
final String externalId = "123L";
final CarportLocation carportLocation = CarportLocationMockHelper.createCarportLocationByIdDTO(externalId);
given(carportService.getCarportLocationToId(externalId.toString())).willReturn(carportLocation);
// when
final MvcResult mvcResult = this.mockMvc.perform(getRequestBuilderMockCarportLocationsById(externalId.toString()))
.andExpect(status().isOk())
.andDo(print())
.andExpect(content().contentType("application/json"))
.andExpect(resultMatcherOK)
.andExpect(MockMvcResultMatchers.jsonPath("$.externalId")
.value(CarportLocation.getExternalId()))
.andReturn();
// then
assertEquals("application/json", mvcResult.getResponse()
.getContentType());
}
public static CarportLocation createCarportLocationByIdDTO(String externalId) {
finalCarportLocation carportLocation = new CarportLocation();
carportLocation.setId(123456L);
carportLocation.setExternalId(externalId);
carportLocation.setCarportName("Carport1");
carportLocation.setLocX(12.4534);
carportLocation.setLocY(19.5678);
carportLocation.setLocZ(25.0);
return carportLocation;
}
这是我用 .andDo(print()) 打印出来的表达式:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /carport/carports/filter
Parameters = {carportNameAndExternalId=[123L]}
Headers = []
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = controller.CarportController
Method = controller.CarportController#_getCarportLocationsByIdAndName(String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = []
Forwarded URL = null
Redirected URL = null
Cookies = []
不幸的是,我的 JUnit 测试失败了,我不知道为什么。
java.lang.AssertionError:JSON 路径“$.externalId”处没有值
当然,我也已经搜索过问题,遇到了如下SO问题:Assertion error: No value for JSON Path in JUnit test
不幸的是,“$[1].externalId”对我没有帮助。因此,andDo(print()) 方法也具有但不能真正处理输出。
有谁知道我必须如何调整 json 路径才能使我的测试成功?
【问题讨论】: