如何在 JUnit [Powermock + Parameterized] 中模拟 System.getenv()

How to mock System.getenv() in JUnit [Powermock + Parameterized]

如何在 JUnit 中模拟 "System.getenv("...")"。

目前我在做:

@RunWith(Parameterized.class)
@PowerMockRunnerDelegate(PowerMockRunner.class)
@PrepareForTest(System.class)
public class TestClass extends BaseTest {

    public TestClass(String testCase) {
        this.testCase = testCase;
    }

    @Before
    @Override
    public final void initTable() throws Throwable {
        super.initTable();
        PowerMockito.mockStatic(System.class); 
        PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");       
    }
...
}

我同时使用 PowerMock 和 Parameterizedrunner。

我遇到以下异常:

PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");

异常:

org.mockito.exceptions.base.MockitoException: 
'afterPropertiesSet' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
    doThrow(exception).when(mock).someVoidMethod();
***

Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case. Use the @PrepareForTest({ClassThatCallsTheSystemClass.class}) annotation at the class-level of the test case.

使用 EasyMock 的示例

public class SystemClassUser {

public String performEncode() throws UnsupportedEncodingException {
    return URLEncoder.encode("string", "enc");
}
  }

并测试

@RunWith(PowerMockRunner.class)
    @PrepareForTest( { SystemClassUser.class })
   public class SystemClassUserTest {

@Test
public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception {
    mockStatic(URLEncoder.class);

    expect(URLEncoder.encode("string", "enc")).andReturn("something");
    replayAll();

    assertEquals("something", new SystemClassUser().performEncode());

    verifyAll();
}
 }

来自: https://github.com/powermock/powermock/wiki/MockSystem

因此,您应该添加一个使用 System.getenv 的 class,而不是 System class 到 @PrepareForTest

post 解释了为什么要这样做。

此外,我想推荐使用 System Rules library for your case. It has a good way to stub environment variables。 PowerMock 修改了一个class 字节码,所以测试很慢。即使它不修改 class,它也至少从磁盘读取 class。