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

rup*_*esh 1 spring-test junit4 mockito powermockito

如何在 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");       
    }
...
}
Run Code Online (Sandbox Code Playgroud)

我同时使用 PowerMock 和 Parameterizedrunner。

我得到以下异常行:

PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");
Run Code Online (Sandbox Code Playgroud)

例外:

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

Art*_*nov 5

在测试用例的类级别使用@RunWith(PowerMockRunner.class) 注释。在测试用例的类级别使用 @PrepareForTest({ClassThatCallsTheSystemClass.class}) 注释。

使用 EasyMock 的示例

public class SystemClassUser {

public String performEncode() throws UnsupportedEncodingException {
    return URLEncoder.encode("string", "enc");
}
  }
Run Code Online (Sandbox Code Playgroud)

并测试

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

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

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

这篇文章解释了为什么应该以这种方式完成。

另外,我想建议为您的案例使用系统规则库。它有一个很好的方法来存根环境变量。PowerMock 修改了一个类的字节码,所以测试很慢。即使它不修改类,它也至少从磁盘读取类。