Eclipse和javac在编译Hamcrest Matcher时的差异

5
我正在尝试在hasItem匹配器中使用来自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编译器和命令行之间的某些差异导致的,但我不确定处理它的最佳方法。

无法重现。您使用的JDK版本是哪个?此外,hasItem()来自哪里? - axtavt
org.hamcrest.Matchers.hasItem()(抱歉,我忘记它是静态导入的。我相信使用的是JDK 1.6.29。) - Matt
3个回答

6
当TypeSafeMatcher实现为内部类时,会出现问题。
将匹配器移动到单个.java文件中应该可以解决您的问题。

这个答案救了我的一天。 - beluchin
你知道为什么吗? - beluchin
1
有人知道为什么Hamcrest TypeSafeMatcher子类不能是内部类,以便在从'mvn test'编译时javac可以工作吗? - Rag

1
我会比较在Eclipse和Maven中使用的JUnit和Hamcrest jars。很多时候,Eclipse会捆绑自己的JUnit和Hamcrest jars,这些与您在Maven pom.xml中定义的可能不同。

0

Maxence 是正确的 - 你使用 TypeSafeMatcher 是问题所在。然而,如果你使用 CustomTypeSafeMatcher ,它应该允许 Maven 构建成功完成。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接