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

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.