Reputation: 1540
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)))
)?
Upvotes: 5
Views: 3823
Reputation: 35598
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).
Upvotes: 7