Java Hamcrest 与 MockMvc:检查键是否存在但值可能为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25318424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:05:36  来源:igfitidea点击:

Hamcrest with MockMvc: check that key exists but value may be null

javahamcrestjsonpathmockmvc

提问by nebulabrot

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.

我正在用 MockMvc 做一些测试,我想验证 JSON 响应的结构。具体来说,我想确保属性的键存在,并且该值是某种类型或 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))))

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

hasKey()是必要的,因为其他断言本身通过,因为 MockMvc 的实现中不存在的键映射为空:

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

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

jsonPath().exists()也不起作用,因为它在内部将值与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);

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

是否有任何聪明的 Hamcrest Matcher 我可以应用于每个属性的单个 json 路径?

采纳答案by Yonatan

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")))

回答by Jeremy D

You can perform this operation with the following existing test classes:

您可以使用以下现有测试类执行此操作:

.andExpect(jsonPath("$..myExpectedNullKey[0]").value(IsNull.nullValue()));

Be sure to import org.hamcrest.core.IsNull

一定要导入 org.hamcrest.core.IsNull

回答by nacho

I have found this solution in this blog:

我在这个博客中找到了这个解决方案:

.andExpect(jsonPath( "$.keyToNull").doesNotExist());

It works for me.

这个对我有用。

回答by ieggel

Here my solution:

这是我的解决方案:

.andExpect(jsonPath("$.object", is(nullValue())));

Hope this helps!

希望这可以帮助!