在静态方法中模拟构造函数

时间:2014-06-04 10:37:37

标签: java unit-testing powermock processbuilder

以下是我试图进行单元测试的代码

public final class ClassToBeTested {
    public static void function(String arg) {
        ProcessBuilder pb = new ProcessBuilder(arg);
        //Using pb here
    }
}

我想在这里模拟构造函数调用(new File(arg)) 我尝试过使用Power Mock:

@PrepareForTest({ClassToBeTested.class})
public class TestClass {
    @Test
    public void functionTest() throws Exception {
        String str = "abc";
        ProcessBuilder mockProcessBuilder = PowerMock.createMock(ProcessBuilder.class);

        PowerMock.expectNew(ProcessBuilder.class, str).andReturn(mockProcessBuilder);

        PowerMock.replay(mockProcessBuilder, ProcessBuilder.class);

        ClassToBeTested.function(abc);

    }
}

这似乎不起作用。因为新的ProcessBuilder(arg)没有返回模拟对象。

1 个答案:

答案 0 :(得分:0)

添加@RunWith(PowerMockRunner.class)有助于解决此问题。

还使用PowerMock.replayAll()