Утверждение значений в массиве, массив без имени - PullRequest
0 голосов
/ 28 мая 2020

Я пытаюсь издеваться над HttpMessageNotReadableException , ниже код Junit 5.

@BeforeEach
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); 
    }

    @Test
    void testHandleHttpMessageNotReadableException() throws Exception {
        String jsonStr = "{\"name\":\"ABC\"}";

        mockMvc.perform(post("/abc/pqr-stu")
                .content(jsonStr)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                //.andExpect(jsonPath("$").isArray())
                //.andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.field", hasItem("somethingId")))
                .andExpect(jsonPath("$.message", hasItem("Something is Mandatory")));

        verify(mockRepository, times(0)).save(any(ModelConfig.class));

    }
  • после издевательства над uri: / abc / pqr-stu

ниже приведены журналы

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /abc/pqr-stu
       Parameters = {}
          Headers = [Content-Type:"application/json", Content-Length:"491"]
             Body = <no character encoding set>
    Session Attrs = {}

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json"]
     Content type = application/json
             Body = [{"field":"somethingId","value":null,"message":"Something is Mandatory"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 6.735 s <<< FAILURE! - in com.XXXControllerTest
[ERROR] testHandleHttpMessageNotReadableException  Time elapsed: 0.269 s  <<< FAILURE!
java.lang.AssertionError: No value at JSON path "$.field"
    at com.controller.XXXControllerTest.testHandleHttpMessageNotReadableException(XXXControllerTest.java:60)
Caused by: com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['field'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
    at com.controller.XXXControllerTest.testHandleHttpMessageNotReadableException(XXXControllerTest.java:60)

Junit result
[INFO] 
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   XXXControllerTest.testHandleHttpMessageNotReadableException:60 No value at JSON path "$.field"

, поэтому из ошибок я понял, что тестовый пример не работает при чтении ответа.

пожалуйста помогите мне, как читать / утверждать поле, значение, сообщение

[{"field":"somethingId","value":null,"message":"Something is Mandatory"}]

1 Ответ

0 голосов
/ 29 мая 2020

код ниже работает нормально

mockMvc.perform(post("/abc/pqr-stu")
                .content(emptyJson).header(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$").isArray())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$.[0].field", is("somethingId")))
                .andExpect(jsonPath("$.[0].message", is("Something is Mandatory")));
...