spring 启动junit mockito空指针异常

spring boot junit mockito null pointer exception

版本信息

Java : 11
Eclipse : 2021-03
Maven : Embedded 3.6

服务Class:

public class BusinessService {

private DataService dataService;

public BusinessService(DataService dataService) {
    super();
    this.dataService = dataService;
}

public int findTheGreatestFromAllData() {
    int[] data = dataService.retrieveAllData();
    int greatest = Integer.MIN_VALUE;

    for (int value : data) {
        if (value > greatest) {
            greatest = value;
        }
    }
    return greatest;
}

}

数据检索 :

public class DataService {
    
    public int[] retrieveAllData() {
        return new int[] { 1, 2, 3, 4, 5 };
    }

}

Junit 测试用例:

@RunWith(MockitoJUnitRunner.class)
public class BusinessServicesMockTest {
    
    @Mock
    DataService dataServiceMock;

    @InjectMocks
    BusinessService businessImpl;
    
    @Test
    public void testFindTheGreatestFromAllData() {
        when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });
        assertEquals(24, businessImpl.findTheGreatestFromAllData());
    }
}

pom.xml

中的依赖项
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

现在,当我 运行 将应用程序作为 Junit 测试时,我得到了以下结果:

java.lang.NullPointerException 
    at BusinessServicesMockTest.testFindTheGreatestFromAllData(BusinessServicesMockTest.java:31)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)

来自第 31 行:

    when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 3 });

进口

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

如何解决这个错误?

您混淆了 JUnit 4 和 JUnit 5 注释。

  • org.junit.jupiter.api.Test 来自 JUnit 5。
  • org.mockito.junit.MockitoJUnitRunner(和一般的跑步者)来自 JUnit 4
  • 在 JUnit 5 中,Runners 已替换为 Extensions

因此,您的跑步者将被忽略,模拟也不会被初始化。 要在 JUnit5 下初始化它们,请改用 MockitoExtension

@ExtendWith(MockitoExtension.class)
public class BusinessServicesMockTest {
//...
}