【问题标题】:Mockito 2 - SpringBoot 1.5.11.RELEASE - Could not initialize class org.mockito.MockitoMockito 2 - SpringBoot 1.5.11.RELEASE - 无法初始化类 org.mockito.Mockito
【发布时间】:2018-05-02 14:06:56
【问题描述】:

我正在尝试使用 Mockito 2.18.3 框架模拟我们公司内部库中提供的final class,不幸的是我们无权更改库中的代码。但是每当我运行时,我都会遇到以下错误:

java.lang.NoClassDefFoundError: Could not initialize class org.mockito.Mockito

at org.springframework.boot.test.mock.mockito.MockReset.get(MockReset.java:107)
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.resetMocks(ResetMocksTestExecutionListener.java:69)
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.resetMocks(ResetMocksTestExecutionListener.java:55)
at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.afterTestMethod(ResetMocksTestExecutionListener.java:50)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:319)

这是我的依赖:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.18.3</version>
        <scope>test</scope>
    </dependency>

这是测试类:

@RunWith(SpringRunner.class)
@TestPropertySource("classpath:application-test.properties")
@SpringBootTest
public class JwtTokenTest {
   @Autowired
   private class JwtValidatorService jwtValidatorService;

   @Mock
   private JwtTokenDetails jwtTokenDetails;

   @Test
   public void jwtGenerateTest() {
      //Code to test JWT generation
   }
}

也根据此链接:https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#unmockable 我创建了 org.mockito.plugins.MockMaker 文件,内容为:mock-maker-inline

我尝试在其他 Stackoverflow 帖子和 Google 中搜索,但仍然没有解决方案。任何人都可以帮助我吗?看起来我错过了一些东西,但未能识别它。由于我在 Mockito 方面没有太多专业知识,因此尝试使用 powermock,但它在下载公司网络中的依赖项时带来了不同的挑战。

如果我需要添加更多代码或更多详细信息,请告诉我。

【问题讨论】:

  • 你是如何运行测试的?
  • 我用的是IntelliJ IDE,右键运行测试类。
  • 嗯,您是否尝试过刷新您的 maven/gradle 项目的干净构建?
  • 是的,我清除了目标文件夹,使用 mvn clean install -U 运行
  • ok.. 我建议您查看测试的运行配置。我可以说 eclipse:测试->右键单击->运行->运行配置。然后查看那里存在的依赖项。很可能您的实际依赖项可能与那些不匹配。

标签: java spring-boot mockito


【解决方案1】:

Spring Boot 1.5.11 与 Mockito 1.x 兼容。具体来说,它使用 1.10.19。与其将 Mockito 的版本覆盖为新的主要版本,不如让 Spring Boot 的依赖管理指定版本。这样做将确保您使用兼容的版本。如果 Mockito 1.10 不能满足您的需求,您需要寻找替代解决方案。

【讨论】:

  • 基本上我想从内部库模拟最终类。这意味着在 Spring Boot 1.5.11 中是不可能的?
  • 如果没有更多信息,很难确定。您的问题没有说明为什么无法初始化 org.mockito.Mockito。您能否更新它以包含所有相关的日志输出,或者更好的是minimal, complete, and verifiable example
  • 从 spring boot 版本 1.5.2.RELEASE 和 2.0.3.RELEASE (and possibly earlier) 开始,spring boot 支持 Mockito 版本 2.X。见commit for README file
【解决方案2】:

Spring Boot 默认使用 Mockito 1.x。但是,可以用 Mockito 2.x 覆盖它,因为 Spring Boot 也可以毫无问题地使用它(参见 this commit)。

为此,只需将此修改添加到您的 POM 文件属性中:

<properties>
    <mockito.version>2.18.3</mockito.version>
</properties>

【讨论】:

  • 这不正确。使用 Spring boot 1.5 覆盖 Mockito 2.X 版本会导致问题。我的单元测试运行正常,但集成测试失败。
猜你喜欢
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 2012-08-01
  • 2012-10-10
  • 2015-11-23
相关资源
最近更新 更多