java - Spring Boot 组件在单元测试中运行时面临空指针
问题描述
我的 Spring Boot 应用程序有一个Controller
使用Service
我创建的 bean ( SharkMaster
) 的 bean,它使用文件中的一些值properties
。
当我在常规模式下运行应用程序时,它工作正常。
但是,当尝试为控制器类运行单元测试并为其提供模拟service
时,它会尝试创建真正的 SharkMaster bean,但由于无法从配置中找到值而失败。
我看了几篇文章 并阅读了一些关于类似问题的博客文章,但在当前阶段,应用程序在NullPointer
尝试以单元测试模式运行时崩溃。
@Configuration
public class SharkMaster{
@Value("${sharkName}")
private String sharkName;
public SharkMaster(){
// sharkName is null here and the NullPointer is thrown
}
控制器测试类:
@RunWith(SpringRunner.class)
@WebMvcTest(SharkController.class)
@ContextConfiguration(classes = {SharkMaster.class})
@TestPropertySource("classpath:application-test.yml")
public class SharkControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private SharkService sharkService;
我试图添加@PropertySource("classpath:application-test.yml")
到 Controller 测试类,但没有帮助。
我相信这个问题与这个问题不同,因为单元测试阶段的情况。
解决方案
删除您的@ContextConfiguration
并尝试这样。
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SharkController.class)
public class SharkControllerTest {
@Autowired
private MockMvc mockMvc;
@InjectMocks
private SharkService sharkService;
@Mock
private SharkMaster sharkMaster;
.......
}
推荐阅读
- json - Scala如何删除地图中的对象
- c++ - asio::ip::tcp::resolver::async_resolve 是否需要外部取消?
- excel - 如何防止我的 UDF 作用于多个工作表?
- swift - 模拟一系列鼠标点击macOS swift
- database - 如何修复颤振中的“未来不是类型”错误?
- python - pyinstaller 与 pyqt 崩溃
- oracle - 使用 PL/SQL 触发显示消息
- javascript - 使用 JavaScript 进行 HEX 等效颜色转换
- unity3d - 2.5D游戏中的角色移动
- android - 使用 Flutter 从路径到文件的转换