简体   繁体   中英

Hamcrest Matcher compilation difference between Eclipse and javac

I am trying to make use of a custom matcher from hamcrest within the hasItem matcher

  @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)));
  }

The matcher looks like this

  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()));
      }
    };
  }

This operates just fine from within eclipse but when built with maven from command line it throws an exception:

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

I know this is a type erasure problem, and that it's due to some difference between the eclipse compiler and the command line, but I am unsure of the best way to handle it.

the problem happens when the TypeSafeMatcher implementation is an inner class.

Moving the matcher to a single .java file should solve your problem.

I would compare the JUnit and Hamcrest jars used in Eclipse as well as Maven. Many times Eclipse bundles its own JUnit and Hamcrest jars that are different than you might have defined in Maven pom.xml

Maxence is correct - your use of TypeSafeMatcher is the problem. However, if you use CustomTypeSafeMatcher instead it should allow the Maven build to complete successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM