Issue
I want to create a JUnit test for this private method:
@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);
}
}
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 = 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.
Answered By - Nel
Answer Checked By - Mary Flores (JavaFixing Volunteer)