简体   繁体   中英

Spring Boot JUnit 5 test failing with null pointer

I am getting

java.lang.NoSuchMethodError: org.junit.jupiter.api.extension.ExtensionContext.getRequiredTestInstances()Lorg/junit/jupiter/api/extension/TestInstances; at org.mockito.junit.jupiter.MockitoExtension.beforeEach(MockitoExtension.java:143) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$null$0(TestMethodTestDescriptor.java:126) at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)

error for below code.

what the proper way of running below code as junit test?

package com.safnas.unittesting.unittesting.business;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.safnas.unittesting.unittesting.data.SomeDataService;

@ExtendWith(MockitoExtension.class)
class SomeBusinessMockTest {
    
    @InjectMocks
    SomeBusinessImpl business = new SomeBusinessImpl();
    
    @Mock
    SomeDataService dataServiceMock;
    
    @Test
    void calculateSumUsingDataService_basic() {
        when(dataServiceMock.retrieveAllData()).thenReturn(new int[] {1,2,3});
        assertEquals(6, business.calculateSumUsingDataService());
    }
    
    @Test
    void calculateSum_empty() {
        when(dataServiceMock.retrieveAllData()).thenReturn(new int[] {});
        assertEquals(0, business.calculateSumUsingDataService());
    }
    
    @Test
    void calculateSum_oneValue() {
        when(dataServiceMock.retrieveAllData()).thenReturn(new int[] {5});
        assertEquals(5, business.calculateSumUsingDataService());
    }

}

I removed @ExtendWith(MockitoExtension.class) and used below

@BeforeEach

void beforeEach() {

MockitoAnnotations.openMocks(this);

}

it worked fine

as per javadocs

AutoCloseable org.mockito.MockitoAnnotations.openMocks(Object testClass)

Initializes objects annotated with Mockito annotations for given testClass:@org.mockito.Mock, @Spy, @Captor, @InjectMocks

See examples in javadoc for MockitoAnnotations class. Parameters:testClass Returns:A closable to close when completing any tests in testClass.

one more observation.

without any change, my original question is working in intelliJ

eclipse is only having issue it seems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM