Question

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.

Was it helpful?

Solution

Adding @RunWith(PowerMockRunner.class) helped to resolve the issue.

Also using PowerMock.replayAll().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top