与MockMvc的Hamcrest:检查密钥是否存在,但值可能为null [英] Hamcrest with MockMvc: check that key exists but value may be null

查看:95
本文介绍了与MockMvc的Hamcrest:检查密钥是否存在,但值可能为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用MockMvc做一些测试,我想验证JSON响应的结构.具体来说,我想确保属性键存在,并且值是某种类型或null.

I'm doing some tests with MockMvc, and I want to validate the structure of a JSON response. Specifically, I want to make sure that the key to an attribute exists, and that the value is of a certain type or null.

{
   "keyToNull": null,  # This may be null, or a String
   "keyToString": "some value"
}

以下内容对我有用,但我想知道是否有一种方法可以将两个期望的每一组合并为一行,因为我要检查很多属性:

The following works for me, but I'm wondering if there's a way to combine each group of two expectations into a single line, as I have a lot of attributes to check:

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;

.andExpect(jsonPath("$").value(hasKey("keyToNull")))
.andExpect(jsonPath("$.keyToNull").value(
                  anyOf(any(String.class), nullValue(String.class))))

.andExpect(jsonPath("$").value(hasKey("keyToString")))
.andExpect(jsonPath("$.keyToString").value(
                  anyOf(any(String.class), nullValue(String.class))))

hasKey()是必需的,因为由于MockMvc实现中不存在的键映射为null,因此另一个断言本身会通过:

The hasKey() is necessary because the other assertion by itself passes since nonexistent keys in MockMvc's implementation map to null:

.andExpect(jsonPath("$.notAKey").value(
                  anyOf(any(String.class), nullValue(String.class)))) // ok

jsonPath().exists()也不起作用,因为它在内部将值与null进行比较.

jsonPath().exists() also doesn't work, because internally it compares the value against null.

我已经考虑过制作这样一个单独的方法:

I've considered making a separate method like this:

private static <T> void assertNullableAttr(ResultActions res, String jsonPath, Class<T> type) throws Exception {
    int split = jsonPath.lastIndexOf('.');
    String prefix = jsonPath.substring(0, split), key = jsonPath.substring(split+1);

    res.andExpect(jsonPath(prefix).value(hasKey(key)))
        .andExpect(jsonPath(jsonPath).value(anyOf(any(type), nullValue(type))));
    }

但是这随后迫使我以一种不自然的方式拆分代码:

But then it forces me to split my code in an unnatural way:

ResultActions res = mockMvc.perform(get("/api"))
    // these attributes must not be null
    .andExpect(jsonPath("$.someInfo").value(hasSize(2)))
        .andExpect(jsonPath("$.someInfo[0].info1").value(any(String.class)))
        .andExpect(jsonPath("$.someInfo[0].info2").value(any(String.class)))
    .andExpect(jsonPath("$.addlInfo").value(hasSize(2)))
        .andExpect(jsonPath("$.addlInfo[0].info1").value(any(String.class)))
        .andExpect(jsonPath("$.addlInfo[0].info2").value(any(String.class)));

// these attributes may be null
assertNullableAttr(res, "$.someInfo[0].info3", String.class);
assertNullableAttr(res, "$.someInfo[0].info4", String.class);

assertNullableAttr(res, "$.addlInfo[0].info3", String.class);
assertNullableAttr(res, "$.addlInfo[0].info4", String.class);

每个属性是否可以将一个聪明的Hamcrest Matcher应用于单个json路径?

Is there any clever Hamcrest Matcher I could apply to a single json path per attribute?

推荐答案

您可以添加以下静态匹配器工厂:

You can add the following static matcher factory:

public static <K> Matcher<Map<? extends K, ?>> hasNullKey(K key) {
    return new IsMapContaining<K,Object>(equalTo(key), anyOf(nullValue(), anyString());
}

然后,您可以像这样使用它:

And then, you can use it like this:

// will succeed, because keyToNull exists and null
.andExpect(jsonPath("$").value(hasNullKey("keyToNull")))

// will succeed, bacause keyToString exists and not null
.andExpect(jsonPath("$").value(hasNullKey("keyToString")))

// will fail, because notAKey doesn't exists
.andExpect(jsonPath("$").value(hasNullKey("notAKey")))

这篇关于与MockMvc的Hamcrest:检查密钥是否存在,但值可能为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆