【发布时间】:2021-06-15 14:47:04
【问题描述】:
版本信息:
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;
如何解决这个错误?
【问题讨论】:
-
代码对我来说非常好。请向我们展示测试中的所有导入。
-
能否提供 build.gradle 或 pom.xml 看看你使用的是哪个版本?
-
@Lemmy : 添加依赖项。请检查。
-
@Lesiak : 添加依赖项。请检查。
-
@Som 我的意思是
BusinessServicesMockTest文件中的导入语句,而不是依赖项
标签: java spring-boot junit mockito