org.powermock.reflect.internal.WhiteboxImpl 对方法 java.lang.Object.clone() 的非法反射访问

Pet*_*zov 6 java spring mocking powermock spring-boot

我想使用这个 JUnit 测试来测试私有方法:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到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

有什么方法可以解决这个问题吗?

Nel*_*Nel 1

已经有几个问题了:

什么是非法反射访问

JDK9:发生了非法反射访问操作。org.python.core.PySystemState

还有一些。

出于测试目的,您只需从您这边执行反射即可,无需使用依赖项。为了更好地理解,我更改了collectEnvironmentData方法的返回类型:

 @EventListener
 private String collectEnvironmentData(ContextRefreshedEvent event) {
    return "Test";
 }
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式访问它来实现假装结果:

    @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);
    }
Run Code Online (Sandbox Code Playgroud)

使用 JDK13,我的控制台上没有警告。