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

我是研究僧i 提交于 2019-12-03 13:46:37

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

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

I have found this solution in this blog:

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

It works for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!