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

标签 java spring unit-testing spring-boot

我的 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/

相关文章:

java - 当每个请求可能需要很长时间才能完成时,如何扩展 TCP 服务器?

java - 套接字,BufferedReader 卡在 readLine()

从 Angular-Cryptography 解密 AES 字符串的 Java 方法

java - 何时在 Spring 中使用 Autowiring

java - Mockito + Spring + @PostConstruct,mock初始化错误,为什么调用@PostConstruct?

java - 更改运行时 spring shell 中的提示符

java - 如何删除ArrayList中对象的属性

spring - Spring Security Grails插件

android - 使用 Robolectric 检查调用的方法

java.lang.NoClassDefFoundError : org/apache/lucene/codecs/simpletext/SimpleTextCodec