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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.