我正在尝试使用hasItem matcher中的hamcrest自定义匹配器
@Test
public void populatesChildCompanies() {
final long firstChildId = 2;
final String firstChildName = "jim";
final long secondChildId = 3;
final String secondChildName = "adam";
final List<Company> childCompanies = asList(createCompanyForRelation(firstChildCid, firstChildName),
createCompanyForRelation(secondChildCid, secondChildName));
company.getChildCompanies().addAll(childCompanies);
final CompanyOverview companyOverview = new CompanyOverview(company);
assertThat(companyOverview.getChildCompanies(), hasItem(companyRelation(firstChildName, firstChildId)));
assertThat(companyOverview.getChildCompanies(), hasItem(companyRelation(secondChildName, secondChildId)));
}
匹配器看起来像这样
public static final Matcher<CompanyRelation> companyRelation(final String name, final long id) {
return new TypeSafeMatcher<CompanyRelation>() {
@Override
protected boolean matchesSafely(final CompanyRelation companyRelation) {
return name.equals(companyRelation.getName()) && id == companyRelation.getId();
}
@Override
public void describeTo(final Description description) {
description.appendText(format("a company relation with a name of %s and a CID of %s", name, id));
}
@Override
protected void describeMismatchSafely(final CompanyRelation companyRelation, final Description description) {
description.appendText(format("[%s, %s]", companyRelation.getName(), companyRelation.getId()));
}
};
}
这在eclipse中运行得很好,但是当从命令行使用maven构建时它会引发异常:
[ERROR] CompanyOverviewTest.java:[96,4] cannot find symbol
[ERROR] symbol : method assertThat(java.util.List<CompanyRelation>,org.hamcrest.Matcher<java.lang.Iterable<? super java.lang.Object>>)
我知道这是一个类型擦除问题,而且这是因为eclipse编译器和命令行之间存在一些差异,但我不确定处理它的最佳方法。
答案 0 :(得分:5)
当TypeSafeMatcher实现是内部类时会发生问题。
将匹配器移动到单个.java文件应该可以解决您的问题。
答案 1 :(得分:1)
我会比较Eclipse和Maven中使用的JUnit和Hamcrest jar。很多时候Eclipse捆绑了自己的JUnit和Hamcrest jar,它们与你在Maven pom.xml中定义的不同
答案 2 :(得分:0)
Maxence是正确的 - 您使用TypeSafeMatcher是个问题。但是,如果您使用CustomTypeSafeMatcher,则应该允许Maven构建成功完成。