Eclipse:无法解析类型 org.hamcrest.core.CombinableMatcher$CombinableBothMatcher。它是从所需的 .class 文件中间接引用的

Eclipse: The type org.hamcrest.core.CombinableMatcher$CombinableBothMatcher cannot be resolved. It is indirectly referenced from required .class files

我正在使用 TestNGMockitoSpring MVC 控制器进行单元测试。我已将 Hamcrest 库包含在 Maven 依赖项中,如下所示。我在这里错过了什么?当我使用以下两种方法时出现错误:

org.hamcrest.Matchers.hasSize;
org.hamcrest.Matchers.is;

以下是我的依赖:

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.9.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.8</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

更新 1:

问题已通过将 hamcrest-library 更改为 hamcrest-all 得到解决。

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

更新 2:

根据 Tunaki 的建议,更好的解决方案是从 mockito 库中排除传递依赖项 hamcrest-core。所以最终的依赖关系应该如下所示:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.8</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

您的 POM 中存在依赖冲突:

  • mockito-core 1.10.8 依赖于 hamcrest-core 1.1.
  • hamcrest-library 1.3 取决于 hamcrest-core 1.3.

Maven 通过选择版本 1.1 (it is declared first and they have equal path) 解决了冲突。

您收到此错误是因为 hamcrest-library 1.3 引用了 CombinableMatcher class that did not exist in version 1.1 but does exist in version 1.3.

如果您真的依赖 Hamcrest 1.3 的特定功能,则需要从 mockito-core 中排除 hamcrest-core 传递依赖(并希望 Hamcrest 1.3 向后兼容 1.1)。否则,只需删除 hamcrest-library 然后您将依赖 Hamcrest 1.1.