2016-10-27 9 views
4

私はちょうど簡単なテストを実行し、IDの値をチェックしようとしていますテストとJSONパス春のテストとJsonPathのprobblem

で問題が生じています:

mockMvc.perform(get("/applications/")).andExpect(status().isOk()) 
     .andDo(print()) 
     .andExpect(content().contentType(TestUtils.APPLICATION_JSON_UTF8)) 
     .andExpect(jsonPath("$", hasSize(4))) 
     .andExpect(jsonPath("$.id",is(1))); 

をしかし、私はエラーを取得します以下のようにします。私のコードはIDの値をチェックする必要がありますように見えます。返されたJSONに複数の項目があるため、十分に具体的ではありませんか?どんな助けもありがとうございます。ありがとう。

 Content type = application/json;charset=UTF-8 
      Body = [{"id":1,"name":"test2"},{"id":2,"name":"test2"}] 
    Forwarded URL = null 
    Redirected URL = null 
      Cookies = [] 

java.lang.AssertionError: No value at JSON path "$.id", exception: Expected to find an object with property ['id'] 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 org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:258) 
    at ... 

答えて

7

私は5分後に答えを見つけました。アレイをより深く理解する必要がありました。これはうまくいきます:

.andExpect(jsonPath("$.[0].id",is(1))); 
+0

正しい形式の '$。[0]'か '$ [0]'ですか? – Whimusical

+0

@Mike正しいのですか? – Abderrahim

+0

それは私のために働いていませんhttps://stackoverflow.com/questions/47818094/json-keys-having-space – paul

2

あなたのJsonPathの式が間違っています。あなたの応答がボディー内にあるからです。 はJsonPath Specificationによると、この構文がすべて正しい:

"$[0][id]" 
"$.[0].[id]" 
"$[0].id" 
"$.0.id" 

これuseful pageはまた、あなたのテストのためのjsonpath式を見つけるためのお手伝いをすることができます。

+0

それは私のために働いていませんhttps://stackoverflow.com/questions/47818094/json-keys-having-space – paul

関連する問題