spring启动junit mockito空指针异常



版本信息

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

服务类别

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;

如何解决此错误?

您混淆了JUnit4和JUnit5注释。

  • org.junit.jupiter.api.Test来自JUnit 5
  • org.mockito.junit.MockitoJUnitRunner(以及一般的运行程序(来自JUnit4
  • 在JUnit 5中,Runner已被Extensions取代

因此,您的runner将被忽略,mock也不会初始化。要在JUnit5下初始化它们,请改用MockitoExtension

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

最新更新