Java 找不到@SpringBootConfiguration
我想为这个私有方法创建一个JUnit测试:Java 找不到@SpringBootConfiguration,java,spring,spring-boot,spring-test,Java,Spring,Spring Boot,Spring Test,我想为这个私有方法创建一个JUnit测试: @Component public class ReportingProcessor { @EventListener private void collectEnvironmentData(ContextRefreshedEvent event) { } } 我试过这个: @ContextConfiguration @SpringBootTest public class ReportingTest { @Aut
@Component
public class ReportingProcessor {
@EventListener
private void collectEnvironmentData(ContextRefreshedEvent event) {
}
}
我试过这个:
@ContextConfiguration
@SpringBootTest
public class ReportingTest {
@Autowired
ReportingProcessor reportingProcessor;
@Test
public void reportingTest() throws Exception {
ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);
}
}
当我运行代码时,我得到:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
您知道我可以如何解决此问题吗?您应该将
@RunWith
与@springbootest
一起使用:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReportingTest {
@Autowired
ReportingProcessor reportingProcessor;
@Test
public void reportingTest() throws Exception {
ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);
}
}
如果没有使用@SpringBootApplication和已知的main()方法对任何类进行注释,则需要将组件类定位在@SpringBootTest注释上 通常我在构建库时会这样做,对于某些特定场景,我需要使用spring上下文对它们进行单元测试 只需在代码中添加以下内容:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ReportingProcessor.class)
public class ReportingTest {
...
刚刚做了,测试正在运行
编辑:不知道您到底想测试什么,只是想展示如何修复您遇到的错误。您是否有一个用
springbootplication
或SpringBootConfiguration
注释的类?您的测试无法工作。如果是这样的话,处理器就已经被调用了。您想测试类/逻辑,还是测试它在启动应用程序时被触发。你的问题还不清楚……我再次得到ReportingTest没有声明任何用@Configuration注释的静态、非私有、非最终的嵌套类,我得到了这个错误的回复!希望有帮助!