簡體   English   中英

Hamcrest Matcher編譯Eclipse和javac之間的區別

[英]Hamcrest Matcher compilation difference between Eclipse and javac

我試圖在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編譯器和命令行之間的一些區別,但我不確定處理它的最佳方法。

TypeSafeMatcher實現是內部類時會發生問題。

將匹配器移動到單個.java文件應該可以解決您的問題。

我會比較Eclipse和Maven中使用的JUnit和Hamcrest罐子。 很多時候,Eclipse捆綁了自己的JUnit和Hamcrest jar,它們與你在Maven pom.xml中定義的不同

Maxence是正確的 - 您使用TypeSafeMatcher是個問題。 但是,如果您使用CustomTypeSafeMatcher,它應該允許Maven構建成功完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM