Search code examples
javaandroidjunitassertions

JUnit assertThat: check that Object equals String


I have Map declared as following:

Map<String, Object> data

I put a String in it and verify its value like this:

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

Now, I'd like to rewrite the verification to use assertThat instead of assertEquals. I've tried the following:

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

And of course it didn't work because of type mismatch:

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

Explicit type cast of the first argument to String helps, but I'd like to avoid it. For example assertEquals doesn't require type cast. So, how can I check that the value, which was put into Map object, declared above, is equal to particular String, using the assertThat method?


Solution

  • The "more assertThat" way of doing things would be:

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

    Please note:

    • Maybe you need type hints for the call to singletonMap
    • Besides the is matcher, there are other matchers that would allow you to check that data contains your "expected" map data

    For your specific problem: that is caused because how generics come into play here; it might be sufficient to use (String) data.get("key") - to tell the compiler that the "actual" argument is of type String.

    In the end - I have no idea what your problem is. I wrote down this piece of code:

    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));
    }
    

    It compiles fine, and the unit test runs and passes. In other words: actually I am unable to repro your problem.