Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 找不到@SpringBootConfiguration_Java_Spring_Spring Boot_Spring Test - Fatal编程技术网

Java 找不到@SpringBootConfiguration

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

我想为这个私有方法创建一个JUnit测试:

@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注释的静态、非私有、非最终的嵌套类,我得到了这个错误的回复!希望有帮助!