java - 模拟自动装配的 bean 会引发 NullPointerException
问题描述
我在 Spring 中有以下类结构。
基类,
public abstract class BaseClass {
@Autowired
protected ServiceA serviceA;
public final void handleMessage() {
String str = serviceA.getCurrentUser();
}
}
我的控制器,
@Component
public class MyController extends BaseClass {
// Some implementation
// Main thing is ServiceA is injected here
}
到目前为止,这工作正常,我可以看到ServiceA
注入也正确。
问题是在ServiceA
下面的测试中进行模拟时。
我的控制器测试,
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class MyControllerTest {
@MockBean
private ServiceA serviceA;
@MockBean
private MyController myController;
@Before
public void init() {
when(serviceA.getCurrentUser()).thenReturn(some object);
}
@Test
public void firstTest() {
myController.handleMessage(); // ---> Throws NPE stating that serviceA is null
}
}
如前所述,它抛出一个NullPointerException
. when.thenReturn
尽管在嘲笑 bean 时没有任何影响,但我不太明白为什么。
解决方案
因为您使用的是 Spring 控制器,所以您需要通过 @Autowired 注释从 SpringContext 导入您的控制器:
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class MyControllerTest {
@MockBean
private ServiceA serviceA;
@Autowired // import through Spring
private MyController myController;
@Before
public void init() {
when(serviceA.getCurrentUser()).thenReturn(some object);
}
@Test
public void firstTest() {
myController.handleMessage(); // ---> Throws NPE stating that serviceA is null
}
}
@MockBean被添加到 SpringContext 中,因此它们将作为依赖项注入到您的控制器中。
推荐阅读
- python - pyspark拟合方法中的MLP分类器错误
- hibernate - Grails 3:SessionFactory Bean没有注入服务
- javascript - 播放时更改 youtube 视频的音量
- windows-7 - 在不注销的情况下重置 Windows 7 显示
- python - 我的简单计算器有什么问题,它不会出错,也不会执行
- android - 当我在数据库中保存此图像的 URI 时,如何在 SQLite 数据库的 imageview 中显示图像?
- django - 为 Django 休息框架视图集操作生成模式
- javascript - 使用 javascript 将图像转换为字节数组
- java-7 - 尝试通过从一个方法读取相同的文本文件到java中的不同方法来优化代码并提高性能
- docker - 具有内部存储库的 GC Cloud Build 自定义构建过程