JUnit assertThat: check that Object is String

I am Mapdeclared as follows:

Map<String, Object> data

I put in it Stringand checked its meaning as follows:

assertEquals("value", data.get("key"));

Now I would like to rewrite the check to use assertThatinstead assertEquals. I tried the following:

assertThat(data.get("key"), equalTo("value"));

And of course, this did not work due to type mismatch:

Wrong 2nd argument type. Found: 'org.hamcrest.Matcher<java.lang.String>', required: 'org.hamcrest.Matcher<? super java.lang.Object>' less...

The explicit type of casting the first argument to Stringhelps, but I would like to avoid it. For example, it assertEqualsdoes not require typing. So, how can I verify that the value that was placed in the object Mapdeclared above is equal to the concrete Stringusing the method assertThat?

+5
2

"more assertThat" :

Map<String, Object> expectedData = Collections.singletonMap("key", "value");

asssertThat(data, is(expectedData));

:

  • , singletonMap
  • , , , , "" .

: , ; (String) data.get("key") -, , "" String.

, , . :

public void test() {
    Map<String, Object> data = new HashMap<>();
    data.put("key", "value");
    assertThat(data.get("key"), is("value"));

    Map<String, Object> expectedData = Collections.singletonMap("key", "value");
    assertThat(data, is(expectedData));
}

, unit test . : .

+3

assertThat (data.get("key"), equalTo ("value"))

    assertThat(data.get("key"), CoreMatchers.equalTo("value"))
0

Source: https://habr.com/ru/post/1657260/


All Articles