如何匹配MockMvc Sp​​ring Test中的对象列表?

时间:2017-02-02 14:52:38

标签: java json spring mockmvc

我有一个MockMVC测试,它返回一个对象列表。我正在尝试检查这个特定的属性设置是否正确。

然而,除了明确添加它之外,我无法使用任何方式进行匹配。 KeyPair是一个带有键值的简单对类,非常类似于地图的条目。

     List<KeyPair<String, String>> keyList = User.getContactDetails()
        .entrySet()
        .stream()
        .map( e -> new KeyPair<String, String>( e ) )
        .collect( Collectors.toList() );

      performQueryWithHeaders( get( "/users/1" ) )
            .andExpect( status().isOk() )
            .andExpect( jsonPath( "$.contactDetails" ,
                  is( keyList ) ) );

我尝试过几个选项

是(keyList)

是(keyList.toString())

是(Gson.toJson(keylist)

是(mapper.writeValueAsString(keyList)(杰克逊序列化)

然而,不断收到不匹配的消息:

    JSON path "$.contactDetails"
Expected: is "[{\"key\":\"example title\",\"value\":\"example title\"},    {\"key\":\"another example\",\"value\":\"another example\"},{\"key\":\"etc \",\"value\":\"etc \"}]"
     but: was <[{"key":"example title","value":"example title"},{"key":"another example","value":"another example"},{"key":"etc ","value":"etc "}]>

 JSON path "$.contactDetails"
Expected: is <[KeyPair(key=example title, value=example title), KeyPair(key=another example, value=another example), KeyPair(key=etc , value=etc )]>
 but: was <[{"key":"example title","value":"example title"},{"key":"another example","value":"another example"},{"key":"etc ","value":"etc "}]>

 JSON path "$.contactDetails"
Expected: is "[KeyPair(key=example title, value=example title), KeyPair(key=another example, value=another example), KeyPair(key=etc , value=etc )]"
 but: was <[{"key":"example title","value":"example title"},{"key":"another example","value":"another example"},{"key":"etc ","value":"etc "}]>

 JSON path "$.contactDetails"
Expected: is "[{\"key\":\"example title\",\"value\":\"example title\"},{\"key\":\"another example\",\"value\":\"another example\"},{\"key\":\"etc \",\"value\":\"etc \"}]"
 but: was <[{"key":"example title","value":"example title"},{"key":"another example","value":"another example"},{"key":"etc ","value":"etc "}]>

我不想在测试中写json,因为看起来有点垃圾/脆弱。那么有人知道如何绘制它吗?

2 个答案:

答案 0 :(得分:0)

问题是JsonPath将$.contactDetails解析为String并将其与List&lt;&gt;进行比较。您可以将keyList转换为字符串并进行比较。

如果要将$.contactDetails解析为列表,我可以建议Gson

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
// ...
Type listType = new TypeToken<List<KeyPair<String, String>>>() {}.getType();
List<KeyPair<String, String>> yourList = new Gson().fromJson(JsonPath.parse("$.contactDetails")), listType);

答案 1 :(得分:0)

试试这个

performQueryWithHeaders( get( "/users/1" ) )
            .andExpect( status().isOk() )
            .andExpect( gson.toJson(jsonPath( "$.contactDetails") ,
                  is( gson.toJson(keyList ) ) );

问题似乎如下 jsonPath( "$.contactDetails")返回一个JsonObject类型的结构,而gson.toJson(keyList )返回一个String,其中包含Json并为引号执行了转义。