Hamcrest Matcher编译Eclipse和javac之间的区别

Mat*_*att 5 java eclipse junit hamcrest maven

我试图在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)));
  }
Run Code Online (Sandbox Code Playgroud)

匹配器看起来像这样

  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()));
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

这可以在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>>)
Run Code Online (Sandbox Code Playgroud)

我知道这是一个类型擦除问题,并且由于eclipse编译器和命令行之间存在一些差异,但我不确定处理它的最佳方法.

Max*_*wil 6

TypeSafeMatcher实现是内部类时会发生问题.

将匹配器移动到单个.java文件应该可以解决您的问题.


Mic*_*son 1

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