首页 > 解决方案 > Mockito 2 - SpringBoot 1.5.11.RELEASE - Could not initialize class org.mockito.Mockito

问题描述

I am trying to mock the final class which is available in our company's internal library using Mockito 2.18.3 framework, unfortunately we don't have access to change the code in the library. But whenever I run I get below error:

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)

This is my dependency:

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

This is the test class:

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

Also as per this link: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#unmockable I have created org.mockito.plugins.MockMaker file with contents: mock-maker-inline.

I tried searching in other Stackoverflow posts and Google, but still not solution. Can anyone kindly help me in this? Looks like I am missing something, but failed to identify it. Since I don't have much expertise in Mockito, tried to use powermock but it is posing different challenges in downloading dependencies in company's network.

Please let me know if I need to add more code or more details.

标签: javaspring-bootmockito

解决方案


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


推荐阅读