The Problem
I'm currently trying to use Hamcrest Matchers to assert that the list type being returned is of a specific type. For example, let's say I have the following List that is being returned by my service call:
List<SomePOJO> myList;
I want to assert that the list being returned is parametrized of type SomePOJO
and not TheOtherPOJO
. However, it appears that Hamcrest Matchers does not have this sort of functionality.
What I Have Tried
After some research, I have seen the following options:
hasItem(isA(SomePJO.class))
, however this only works if there is an element in the list, and not if the list is empty.is(instanceOf(List.class))
, however this will only assert that the item being returned is a List; it does not assert what type of list is being returned.assertThat(somePojo.get(0), is(instanceOf(SomePOJO.class)))
, however this isn't very clean. It is also very similar to point #1.Conclusion / The Question
Using Hamcrest Matchers, is there a way to assert that an empty list is parametrized of a certain type (such as assertThat(myList, is(aListOf(SomePOJO.class)))
)?
Hamcrest is used for unit testing in Java. The goal of Hamcrest is to make it easier to read and write test cases. We use Hamcrest to write the matcher objects that allow us to define the match rules declarative.
Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.
Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.
To check tha collection contains items in expected (given) order you can use Hamcrest's containsInRelativeOrder method.
You can't. This is due to type erasure, you're not able to inspect the generic type. The compiler will enforce this for you. If you really want to test this, one option would be to grab the first element and make sure you can cast it to SomePOJO
. (or alternatively grab every element and attempt the cast, but I believe this is overkill).
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