Java 在单元测试中运行时,Spring引导组件面对空指针

Java 在单元测试中运行时,Spring引导组件面对空指针,java,spring,unit-testing,spring-boot,Java,Spring,Unit Testing,Spring Boot,我的Spring Boot应用程序有一个控制器,它使用一个服务,该服务使用我创建的bean(SharkMaster),该bean使用属性文件中的一些值 当我在常规模式下运行应用程序时,它工作正常 但是,当尝试为控制器类运行单元测试并为其提供模拟服务时,它尝试创建真正的SharkMaster bean,但失败了,因为它无法从配置中找到值 我看到并阅读了一些类似的问题,但在当前阶段,当试图在单元测试模式下运行时,应用程序在NullPointer中崩溃 @Configuration public cl

我的Spring Boot应用程序有一个
控制器
,它使用一个
服务
,该服务使用我创建的bean(
SharkMaster
),该bean使用
属性
文件中的一些值

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

但是,当尝试为控制器类运行单元测试并为其提供模拟
服务时,它尝试创建真正的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”)
添加到控制器测试类,但没有任何帮助


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

删除您的
@ContextConfiguration
,然后像这样尝试

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

@Autowired
private MockMvc mockMvc;

@InjectMocks
private SharkService sharkService;

@Mock
private SharkMaster sharkMaster;

.......
}

plz在执行此操作时引用此项,错误是不同的:没有可用的“SharkMaster”类型的合格bean。另一种方法是,创建SharkMaster的模拟,并执行@InjectMocks for SharkService#pvpkiran来完成此操作。谢谢