为什么尝试使用 Hamcrest 的 hasItems 的代码不能编译? [英] Why doesn't this code attempting to use Hamcrest's hasItems compile?

查看:16
本文介绍了为什么尝试使用 Hamcrest 的 hasItems 的代码不能编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个编译不通过,哦,怎么办?

Why does this not compile, oh, what to do?

import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItems;

ArrayList<Integer> actual = new ArrayList<Integer>();
ArrayList<Integer> expected = new ArrayList<Integer>();
actual.add(1);
expected.add(2);
assertThat(actual, hasItems(expected));

从评论中复制的错误:

cannot find symbol method assertThat(java.util.ArrayList<java.lang.Integer>, org.hamcreset.Matcher<java.lang.Iterable<java.util.ArrayList<java.lang.Integer>>>)

推荐答案

刚遇到这篇试图为自己修复的帖子.给了我足够的信息来解决这个问题.

Just ran into this post trying to fix it for myself. Gave me just enough information to work it out.

您可以通过将 hasItems 的返回值转换为(原始)Matcher 来让编译器足以说服它进行编译,例如:

You can give the compiler just enough to persuade it to compile by casting the return value from hasItems to a (raw) Matcher, eg:

ArrayList<Integer> actual = new ArrayList<Integer>();
ArrayList<Integer> expected = new ArrayList<Integer>();
actual.add(1);
expected.add(2);
assertThat(actual, (Matcher) hasItems(expected));

以防万一其他人还在受苦......

Just in case anybody else is still suffering ...

编辑添加:尽管获得了赞成票,但正如 Arend 在下面指出的那样,这个答案是错误的.正确 答案是将预期转换为整数数组,正如 hamcrest 所期望的那样:

Edit to add: In spite of the up votes, this answer is wrong, as Arend points out below. The correct answer is to turn the expected into an array of Integers, as hamcrest is expecting:

    ArrayList<Integer> actual = new ArrayList<Integer>();
    ArrayList<Integer> expected = new ArrayList<Integer>();
    actual.add(1);
    expected.add(2);
    assertThat(actual, hasItems(expected.toArray(new Integer[expected.size()])));

这篇关于为什么尝试使用 Hamcrest 的 hasItems 的代码不能编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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