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