How to test if JSON path does not include a specific element, or if the element is present it is null?

前端 未结 5 1309
野趣味
野趣味 2021-02-04 23:17

I have been writing some simple unit testing routines for a simple spring web application. When I add @JsonIgnore annotation on a getter method of a resource, the resulting json

5条回答
  •  误落风尘
    2021-02-04 23:33

    I wanted to reuse the same code I use for testing for the parameter being supplied, and for it missing, and this is what I came up with

      @Test
      void testEditionFoundInRequest() throws JsonProcessingException {
        testEditionWithValue("myEdition");
      }
    
      @Test
      void testEditionNotFoundInRequest() {
        try {
          testEditionWithValue(null);
          throw new RuntimeException("Shouldn't pass");
        } catch (AssertionError | JsonProcessingException e) {
          var msg = e.getMessage();
          assertTrue(msg.contains("No value at JSON path"));
        }
      }
    
    
      void testEditionWithValue(String edition) {   
       var HOST ="fakeHost";
       var restTemplate = new RestTemplate();
       var myRestClientUsingRestTemplate = new MyRestClientUsingRestTemplate(HOST, restTemplate);
       MockRestServiceServer mockServer;
       ObjectMapper objectMapper = new ObjectMapper();
       String id = "userId";
       var mockResponse = "{}";
    
       var request = new MyRequest.Builder(id).edition(null).build();
       mockServer = MockRestServiceServer.bindTo(restTemplate).bufferContent().build();
    
       mockServer
            .expect(method(POST))
    
            // THIS IS THE LINE I'd like to say "NOT" found
            .andExpect(jsonPath("$.edition").value(edition))
            .andRespond(withSuccess(mockResponse, APPLICATION_JSON));
    
        var response = myRestClientUsingRestTemplate.makeRestCall(request);
      } catch (AssertionError | JsonProcessingException e) {
        var msg = e.getMessage();
        assertTrue(msg.contains("No value at JSON path"));
      }
    

提交回复
热议问题