Search code examples
javaspringspring-bootspring-test

Unable to find a @SpringBootConfiguration


I want to create a JUnit test for this private method:

@Component
public class ReportingProcessor {

    @EventListener
    private void collectEnvironmentData(ContextRefreshedEvent event) {
    }
}

I tried this:

@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);

    }
}

When I run the code I get:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

Do you know ho I can fix this issue?


Solution

  • If you don't have any class annotated with @SpringBootApplication and the known main() method, you need to target your component class on the @SpringBootTest annotation.

    Usually I do this when I'm building libraries and for some specific scenario I need to have the spring context to unit test them.

    Just add this to your code:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = ReportingTest.class)
    public class ReportingTest {
    ...
    

    In JUnit 5 @RunWith(SpringRunner.class) is not needed