gpt4 book ai didi

java - Spring Boot组件在单元测试中运行时面临空指针

转载 作者:行者123 更新时间:2023-12-02 11:11:34 24 4
gpt4 key购买 nike

我的 Spring Boot 应用程序有一个 Controller使用 Service它使用我创建的 bean ( SharkMaster ),该 bean 使用 properties 中的一些值文件。

当我在常规模式下运行应用程序时,它工作正常。

但是,当尝试为 Controller 类运行单元测试并为其提供模拟时 service它尝试创建真正的 SharkMaster bean,但由于无法从配置中找到值而失败。

我看到了several posts并阅读一些blog posts关于类似的问题,但在当前阶段,该应用程序正在崩溃 NullPointer当尝试在单元测试模式下运行时。

@Configuration
public class SharkMaster{

@Value("${sharkName}")
private String sharkName;

public SharkMaster(){
// sharkName is null here and the NullPointer is thrown
}

Controller 测试类:

@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 测试类,但没有帮助。

我相信这个问题与this one不一样。 ,因为这里的情况是在单元测试阶段。

最佳答案

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

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

@Autowired
private MockMvc mockMvc;

@InjectMocks
private SharkService sharkService;

@Mock
private SharkMaster sharkMaster;

.......
}

关于java - Spring Boot组件在单元测试中运行时面临空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50580108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com