Hamcrest Matchers-断言列表类型 [英] Hamcrest Matchers - Assert Type of List

查看:245
本文介绍了Hamcrest Matchers-断言列表类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我目前正在尝试使用Hamcrest Matchers断言所返回的列表类型是特定类型.例如,假设我的服务呼叫返回了以下列表:

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;

我想断言所返回的列表的参数类型为SomePOJO而不是TheOtherPOJO.但是,似乎Hamcrest Matchers没有这种功能.

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.

我尝试过的事情

经过研究,我看到了以下选项:

After some research, I have seen the following options:

  1. 我已经看到有hasItem(isA(SomePJO.class)),但是这仅在列表中有一个元素时才有效,而在列表为空时则不起作用.
  2. 可以使用is(instanceOf(List.class)),但这只会断言所返回的项目是一个列表;它不声明要返回哪种类型列表.
  3. 我还可以在assert语句之前紧接着将元素添加到列表中,然后使用assertThat(somePojo.get(0), is(instanceOf(SomePOJO.class))),但这不是很干净.它也与第1点非常相似.
  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.

结论/问题

使用Hamcrest Matchers,有没有办法断言已对某种类型的空列表进行了参数化设置(例如assertThat(myList, is(aListOf(SomePOJO.class))))?

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

推荐答案

您不能.这是由于类型擦除造成的,您无法检查泛型类型.编译器将为您强制执行此操作.如果您真的要测试它,一个选择是获取第一个元素,并确保可以将其强制转换为SomePOJO. (或另选每个元素并尝试投射,但我认为这太过分了.)

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

这篇关于Hamcrest Matchers-断言列表类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆