@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问题:断言错误:JUnit测试中的JSON路径没有值
只是不幸的是$[1] externalId";因此,andDo(print())
方法也有,但不能真正处理输出。有人知道我必须如何调整json路径才能成功测试吗?
根据以下内容:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json"]
Content type = application/json
Body = []
Forwarded URL = null
Redirected URL = null
Cookies = []
The response body is empty.
没有返回JSON响应,那么您如何期待"$.externalId
";被发现?
此外,格式应为:
.andExpect(jsonPath("$.externalId", is(CarportLocation.getExternalId())))