6

I want to use this JUnit test for testing private method:

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

    @Autowired
    ReportingProcessor reportingProcessor;

    @Test
    public void reportingTest() throws Exception {

        ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
        Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);

    }
}

But I get WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.powermock.reflect.internal.WhiteboxImpl (file:/C:/Users/Mainuser/.m2/repository/org/powermock/powermock-reflect/2.0.2/powermock-reflect-2.0.2.jar) to method java.lang.Object.clone() WARNING: Please consider reporting this to the maintainers of org.powermock.reflect.internal.WhiteboxImpl WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release

Is there some way to fix this?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

1

There are already a few questions about it:

what is an illegal reflective access

JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

and a few more.

For testing purposes, you can just perform the reflection from your side, with no need to use dependencies. I have changed the return type of the collectEnvironmentData method just for a better understanding:

 @EventListener
 private String collectEnvironmentData(ContextRefreshedEvent event) {
    return "Test";
 }

You can achieve the pretended result by accessing it this way:

    @Test
    public void reportingTest() throws Exception {

        ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);

        Method privateMethod = ReportingProcessor.class.
                getDeclaredMethod("collectEnvironmentData", ContextRefreshedEvent.class);

        privateMethod.setAccessible(true);

        String returnValue = (String)
                privateMethod.invoke(reportingProcessor, contextRefreshedEvent);
        Assert.assertEquals("Test", returnValue);
    }

No warnings on my console, with JDK13.

Nel
  • 124
  • 6
  • When I compile the entire project it's running well. But when I compile only this JUnit test I get `java.lang.Exception: No runnable methods at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)` – Peter Penzov Oct 18 '19 at 09:10
  • Check if you are using the right annotation: import org.junit.Test; – Nel Oct 18 '19 at 09:29
  • I removed @RunWith(SpringRunner.class) and now it's working fine. Is this correct? – Peter Penzov Oct 18 '19 at 09:32