Sunday, February 8, 2015

is(nullValue()) and doesNotExist() for jayway.jsonpath

There are Account and AccountResource in my application. For testing, I add @JsonIgnore before my getPassword() method so that it won't return password for my test.

I use jayway.jsonpath to validate those returned value;
If the version of jayway.jsonpath is 0.9 and older, is(nullValue()) can be used:

mockMvc.perform(get("/rest/accounts/1"))
        .andDo(print())
        .andExpect(jsonPath("$.password", is(nullValue())))



But for any newer version, the is(nullValue()) will throw exception:



java.lang.AssertionError: No value for JSON path: $.password, exception: No results for path: $['password']
 at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:101)
 at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:91)
 at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:56)
 at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
 at firstapp.mvc.AccountControllerTest.getExistingAccount(AccountControllerTest.java:142)



To solve this problem for any version that is later than 0.9, we use the doesNotExist() instead, i.e:



mockMvc.perform(get("/rest/accounts/1"))
       .andDo(print())
       .andExpect(jsonPath("$.password").doesNotExist())

No comments:

Post a Comment