【问题标题】:Illegal reflective access by org.powermock.reflect.internal.WhiteboxImpl to method java.lang.Object.clone()org.powermock.reflect.internal.WhiteboxImpl 对方法 java.lang.Object.clone() 的非法反射访问
【发布时间】:2019-10-17 22:53:22
【问题描述】:

我想用这个 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);

    }
}

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

有没有办法解决这个问题?

【问题讨论】:

    标签: java spring spring-boot mocking powermock


    【解决方案1】:

    已经有几个问题了:

    what is an illegal reflective access

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

    还有更多。

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

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

    您可以通过这种方式访问​​它来实现假装的结果:

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

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

    【讨论】:

    • 当我编译整个项目时,它运行良好。但是当我只编译这个 JUnit 测试时,我得到 java.lang.Exception: No runnable methods at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
    • 检查是否使用了正确的注解:import org.junit.Test;
    • 我删除了@RunWith(SpringRunner.class) 现在它工作正常。这是正确的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多