Hamcrest Matchers - Assert Type of List

2019-06-22 15:04发布

问题:

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:

  1. I have seen that there is hasItem(isA(SomePJO.class)), however this only works if there is an element in the list, and not if the list is empty.
  2. I could use 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.
  3. I can also add an element to the list immediately before the assert statement and then using 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))))?

回答1:

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).