2

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?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • Do you have a class annotated with `SpringBootApplication` or `SpringBootConfiguration`? – Gustavo Passini Oct 16 '19 at 23:36
  • YOur test won't work. If it would the processor would already be invoked. Do you want to test the class/logic or the fact that it is triggered upon starting your application. That isn't clear from your question... – M. Deinum Oct 17 '19 at 05:44

3 Answers3

2

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 = ReportingProcessor.class)
public class ReportingTest {
...

Just did it and the test is running.

Edit: Don't know what are you trying to test exactly, just wanted to show how can you fix the error you are getting.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
Nel
  • 124
  • 6
0

You should use the @RunWith with your @SpringBootTest:

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

    }
}
Villat
  • 1,455
  • 1
  • 16
  • 33
  • I get again `ReportingTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration` – Peter Penzov Oct 17 '19 at 16:19
0

For future lost souls: in my case reason of this exception was that I created Junit test without package specified.

Your test must be in subpackage of your main spring class (one annotated with @SpringBootApplication). So if you have com.example.Application then your test must be in some sub package, for example com.example.subpackage.

nouveu
  • 162
  • 4
  • 9