java - InjectMocks 对象在单元测试中为空
问题描述
这是我第一次使用 Mockito 进行 junit 测试。我正面临@InjectMocks 中使用的服务的 NPE 问题。我查看了其他解决方案,但即使遵循它们,它也显示相同。这是我的代码。
@RunWith(MockitoJUnitRunner.class)
public class CustomerStatementServiceTests {
@InjectMocks
private BBServiceImpl bbService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
/**
* This test is to verify SUCCESS response
*/
@Test
public void testSuccess() {
BBResponse response = bbService.processDetails(txs);
assertEquals("SUCCESSFUL" ,response.getResult());
}
}
BBServiceImpl
@Service
public class BBServiceImpl implements BBService {
final static Logger log = Logger.getLogger(BBServiceImpl.class);
public BBResponse process(List<Customer> customers) {
// My business logic goes here
}
}
Pom.xml
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
我的“bbService”对象在这里为空
我在这里错过了什么吗?
解决方案
在提供了额外信息的讨论之后,答案可以总结为junit4
和之间的 Maven 配置问题junit5
。
java.lang.NullPointerException
at com.cts.rabo.CustomerStatementServiceTests.testSuccess(CustomerStatementServiceTests.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
...
堆栈跟踪显示了junit5
引擎的明确用法。
pom 还包括以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.2.5.RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
在 Spring Boot 2.2.0.RELEASE 之前,spring-boot-starter-test 包含 junit4 依赖传递。从 Spring Boot 2.2.0 开始,Junit Jupiter 被包括在内。
根据这个答案,排除似乎阻止了执行。
删除排除为我解决了这个问题。
junit5
如果没有明显的使用要求,我建议切换到junit4
.
检查此答案以获取有关如何与mockito
一起使用的更多信息junit5
。
推荐阅读
- json - 使用带有 JSON 响应的 React 来获取 API 数据
- java - 使用Java,如何在数组的开头将一些节点添加到现有的json?
- firebase - 如果我只使用flutter web(没有android或ios应用程序),我还应该在index.html和main.dart中初始化firebase应用程序两次吗?
- internationalization - 为什么我的 Forge 翻译文件不起作用?
- scikit-learn - 在 sklearn 中的整个管道中保留或获取特征名称(XGBoost 特征重要性)
- php - 如何在 Laravel 8 的模板中使用不同的数据将单个电子邮件发送给多个收件人
- alpha-vantage - 来自 Alphavantage API 的股票分割信息
- sqlite - Microsoft.EntityFrameWork 中的 SQLite 加密
- reactjs - react-beautiful-dnd 中的“无法找到拖动手柄”错误
- java - 由于使用注释生成方法,如何抑制警告“无法解析方法”?