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?
The assertSame() method tests if two object references point to the same object. The assertNotSame() method tests if two object references do not point to the same object. void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other.
assertEquals() calls equals() on your objects, and there is no way around that. What you can do is to implement something like public boolean like(MyClass b) in your class, in which you would compare whatever you want. Then, you could check the result using assertTrue(a. like(b)) .
You should always use . equals() when comparing Strings in Java. JUnit calls the . equals() method to determine equality in the method assertEquals(Object o1, Object o2) .
The assertThat is one of the JUnit methods from the Assert object that can be used to check if a specific value match to an expected one. It primarily accepts 2 parameters. First one if the actual value and the second is a matcher object.
The "more assertThat" way of doing things would be:
Map<String, Object> expectedData = Collections.singletonMap("key", "value");
asssertThat(data, is(expectedData));
Please note:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With