Following is the code I am trying to unit test
public final class ClassToBeTested {
public static void function(String arg) {
ProcessBuilder pb = new ProcessBuilder(arg);
//Using pb here
}
}
I want to mock the constructor invocation (new File(arg)), here I tried using 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);
}
}
This doesn't seem to work. As new ProcessBuilder(arg) is not returning the mocked object.
Adding @RunWith(PowerMockRunner.class)
helped to resolve the issue.
Also using PowerMock.replayAll()
.