首页 > 解决方案 > 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 测试类,但没有帮助。

我相信这个问题与这个问题不同因为单元测试阶段的情况。

标签: javaspringunit-testingspring-boot

解决方案


删除您的@ContextConfiguration并尝试这样。

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SharkController.class)
public class SharkControllerTest {

@Autowired
private MockMvc mockMvc;

@InjectMocks
private SharkService sharkService;

@Mock
private SharkMaster sharkMaster;

.......
}

推荐阅读