1

使用 Powermock 2.x 模拟系统类在验证调用时失败。使用 Powermock 1.x 版本成功通过了相同的测试。

班级:

public class SysConfigurer {
    public void setConfig(String key, String value){
        System.setProperty(key, value);
    }
}

测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Validator.class)
@PowerMockIgnore("javax.management.*")
public class SysConfigurerTest {
    @Test
    public void testSystemConfig() {
        mockStatic(System.class);
        PowerMockito.when(System.setProperty("foo", "bar")).thenReturn("fab");
        assertThat(new SysConfigurer().set("foo", "bar"), is("fab"));
        verifyStatic(System.class);
        System.setProperty("foo", "bar");
    }
}

Maven 依赖项

[INFO] +- net.bytebuddy:byte-buddy:jar:1.8.3:test
[INFO] +- junit:junit:jar:4.12:test
[INFO] +- org.powermock:powermock-reflect:jar:2.0.0-RC.4:test
[INFO] |  +- org.objenesis:objenesis:jar:3.0.1:test
[INFO] |  \- net.bytebuddy:byte-buddy-agent:jar:1.9.3:test
[INFO] +- org.powermock:powermock-core:jar:2.0.0-RC.4:test
[INFO] |  \- org.javassist:javassist:jar:3.24.0-GA:compile
[INFO] +- org.powermock:powermock-api-mockito2:jar:2.0.0-RC.4:test
[INFO] |  \- org.powermock:powermock-api-support:jar:2.0.0-RC.4:test
[INFO] +- org.powermock:powermock-module-junit4:jar:2.0.0-RC.4:test
[INFO] |  \- org.powermock:powermock-module-junit4-common:jar:2.0.0-RC.4:test
[INFO] +- org.mockito:mockito-core:jar:2.23.4:test
[INFO] \- org.hamcrest:hamcrest-junit:jar:2.0.0.0:test

错误:

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

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.lang.System
Mockito cannot mock/spy because :
 - final class

at ValidatorTest.testSystemConfig(SysConfigurerTest.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
4

0 回答 0