Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix this error: java.lang.NoSuchMethodError: 'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'

So I am getting this error in my Spring boot Gradle project:

'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'
    java.lang.NoSuchMethodError: 'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'

And I cannot seem to fix it. I have searched for the answer but the only one I get is removing mockito-all from your dependencies, but I do not have that in my gradle.build file in the first place.

My build.gradle file:

plugins {
    id 'org.springframework.boot' version '2.4.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id "org.sonarqube" version "3.0"
    id 'jacoco'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}


dependencies {
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    implementation('io.jsonwebtoken:jjwt:0.2')
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile 'junit:junit:4.12'
    implementation 'org.modelmapper:modelmapper:2.4.1'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.eclipse.jgit:org.eclipse.jgit:5.4.2.201908231537-r'
    /**
     * JUnit jupiter with mockito.
     */
    testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.19.0'

    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
    testCompile group: 'org.springframework.security', name: 'spring-security-test', version: '5.1.6.RELEASE'
}

sonarqube{
    properties{
        property 'sonarjava.source', '1.8'
        property 'sonar.java.coveragePlugin', 'jacoco'
        property 'sonar.jacoco.reportPaths', 'build/reports/jacoco/test/jacocoTestReport.xml'
    }
}
test {
    useJUnitPlatform()
}

I can't seem to find a solution so I came to here, where some code god maybe can help me fixing my problem.

The file where I get this error on is a test class:

The test class:

package com.example.demo.Service;

import com.example.demo.DTO.PartyLeaderDto;
import com.example.demo.Model.PartyLeader;
import com.example.demo.Repository.PartyLeaderRepository;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.verify;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.modelmapper.ModelMapper;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Optional;

import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.argThat;

@SpringBootTest
@AutoConfigureMockMvc
public class PartyLeaderServiceMockTest {
    @Rule
    public MockitoRule initRule = MockitoJUnit.rule();

    @Mock
    private PartyLeaderRepository partyLeaderRepository;

    @Mock
    private ModelMapper modelMapper;

    @InjectMocks
    private PartyLeaderService partyLeaderService; // this is like calling new PartyLeaderService(partyLeaderRepository, modelMapper);


    @Test
    void whenSavePartyLeader_thenCorrectPartyLeaderSaved() {
        // given
        var input = PartyLeaderDto.builder()
                .name("Josse")
                .apperance("Link of image")
                .build();

        // when
        partyLeaderService.savePartyLeader(input);


        // then
        verify(partyLeaderRepository).save(argThat(entity ->
                entity.getName().equals("Josse")
                        && entity.getApperance().equals("Link of image")));
    }


    @Test
    void whenGetPartyLeader_ShouldReturnCorrectLeaderData() {
        // given
        var partyLeaderEntity = PartyLeader.builder()
                .name("Josse")
                .apperance("Link of image")
                .build();
        var partyLeaderDto = PartyLeaderDto.builder()
                .name("Josse")
                .apperance("Link of image")
                .build();
        when(partyLeaderRepository.findById(3)).thenReturn(Optional.of(partyLeaderEntity));
        when(modelMapper.map(partyLeaderEntity, PartyLeaderDto.class)).thenReturn(partyLeaderDto);

        // when
        var result = partyLeaderService.getPartyLeader(3);

        // then
        Assert.assertEquals(result, partyLeaderDto);
    }
}

I get the same error on both of my tests.

Can anyone help me? Thanks in advance!

like image 328
LardinoisJosse Avatar asked Dec 13 '22 07:12

LardinoisJosse


2 Answers

Issue was due to the jar conflicts

We need to exclude

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

And include

<dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.11.2</version>
    </dependency>
like image 111
nithin prasad Avatar answered May 08 '23 09:05

nithin prasad


After facing the same issue. Please look log trace.

java.lang.NoSuchMethodError: org.mockito.MockitoAnnotations.openMocks(Ljava/lang/Object;)Ljava/lang/AutoCloseable;
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.initMocks(MockitoTestExecutionListener.java:83)

Finally got a solution:

In Mockito version 2 there is a MockitoAnnotations.initMock() method, which is deprecated and replaced with MockitoAnnotations.openMocks() in Mockito JUnit 5 version 3. The MockitoAnnotations.openMocks() method returns an instance of AutoClosable which can be used to close the resource after the test.

Manual Initialization

Before doing anything else, we have to add the Mockito dependency.

dependencies {
    testImplementation('org.mockito:mockito-core:3.7.7')
}

The MockitoAnnotations.openMocks(this) call tells Mockito to scan this test class instance for any fields annotated with the @Mock annotation and initialize those fields as mocks.

Pros:

Easy to create mocks Very readable

Cons:

Does not validate framework usage or detect incorrect stubbing Automatic Mock Injection We can also tell Mockito to inject mocks automatically to a field annotated with @InjectMocks.

When MockitoAnnotations.openMocks() is called, Mockito will:

Create mocks for fields annotated with the @Mock annotation Create an instance of the field annotated with @InjectMocks and try to inject the mocks into it Using @InjectMocks is the same as we did when instantiating an instance manually, but now automatic.

public class MockitoInjectMocksTests {

    @Mock
    private OrderRepository orderRepository;
    private AutoCloseable closeable;
    @InjectMocks
    private OrderService orderService;

    @BeforeEach
    void initService() {
        closeable = MockitoAnnotations.openMocks(this);
    }

    @AfterEach
    void closeService() throws Exception {
        closeable.close();
    }

    @Test
    void createOrderSetsTheCreationDate() {
        Order order = new Order();
        when(orderRepository.save(any(Order.class))).then(returnsFirstArg());

        Order savedOrder = orderService.create(order);

        assertNotNull(savedOrder.getCreationDate());
    }
}

Mockito will first try to inject mocks by constructor injection, followed by setter injection, or field injection.

Pros:

Easy to inject mocks

Cons:

Doesn’t enforce usage of constructor injection

like image 20
Praveen Kumar Verma Avatar answered May 08 '23 08:05

Praveen Kumar Verma