Search code examples
junitmockitojunit4junit5

Migration issue from Junit 4 to Junit 5


I am migrating my codebase from junit4 to junit5.I have used mockito in my testcase.Below are the different version that i am using for the dependency.

<junit.jupiter.version>5.2.0</junit.jupiter.version>
<junit.platform.version>1.2.0</junit.platform.version>
<org.mockito.version>1.10.19</org.mockito.version>

   <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>2.19.0</version>
        <scope>test</scope>
    </dependency>

I have used the annotation @RunWith(MockitoJUnitRunner.class) to run my mockito code.Replaced the same with @ExtendWith(MockitoExtension.class)

But when i run the test case i get the below error. Any suggestion to solve this issue. I suspect is there any dependency version issue which is causing this problem.

java.lang.NoClassDefFoundError: org/mockito/quality/Strictness
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructor0(Class.java:3075)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at..

Thanks -Sam


Solution

  • The JUnit5 MockitoExtension uses org.mockito.quality.Strictness so in order to use MockitoExtension you'll need to use a version of mockito-core which contains org.mockito.quality.Strictness. mockito-core:1.10.19 does not contain that class because that class was added in Mockito 2.x. So, in order to use MockitoExtension you'll need to use at least version 2.x of mockito-core.

    The Mockito docs don't make this explicit but I suspect the expectation is that you'll use the same Mockito version for mockito-core and for mockito-junit-jupiter.

    The following dependencies will allow you to use the JUnit5 MockitoExtension successfully:

    <org.mockito.version>2.19.0</org.mockito.version>
    
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>${org.mockito.version}</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>${org.mockito.version}</version>
        <scope>test</scope>
    </dependency>