Hamcrest Matchers - Assert Type of List

点点圈 提交于 2019-12-10 14:39:30

问题


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



来源:https://stackoverflow.com/questions/23935414/hamcrest-matchers-assert-type-of-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!