Mock java.lang.Runtime with PowerMockito

want to write unittest for a method like

public static void startProgram() {
    process = Runtime.getRuntime().exec(command, null, file);
}

I don’t want to introduce a runtime object for some reason, so I wanted to drown out the getRuntime method that returns the Runtime layout ... I tried it like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Runtime.class)
public class ProgramTest {

    @Test
    public void testStartProgram() {
        Runtime mockedRuntime = PowerMockito.mock(Runtime.class);

        PowerMockito.mockStatic(Runtime.class);
        Mockito.when(Runtime.getRuntime()).thenReturn(mockedRuntime);

        ... //test
    }
}

But that does not work. In fact, nothing seems to be bullied. The test uses a regular Runtime object.

Any idea why this doesn't work and / or how it works?

Since this mini-example does not seem to reproduce the problem, here is the full test code: method for checking (shortened)

public static synchronized long startProgram(String workspace) {
    // Here happens someting with Settings which is mocked properly
    File file = new File(workspace);
    try {
        process = Runtime.getRuntime().exec(command, null, file);
    } catch (IOException e) {
        throw e;
    }
    return 0L;
}

and test:

@Test
public void testStartProgram() {
    PowerMockito.mockStatic(Settings.class);
    Mockito.when(Settings.get("timeout")).thenReturn("42");

    Runtime mockedRuntime = Mockito.mock(Runtime.class);
    // Runtime mockedRuntime = PowerMockito.mock(Runtime.class); - no difference
    Process mockedProcess = Mockito.mock(Process.class);

    Mockito.when(mockedRuntime.exec(Mockito.any(String[].class), Mockito.any(String[].class),
                    Mockito.any(File.class))).thenReturn(mockedProcess);

    PowerMockito.mockStatic(Runtime.class);
    Mockito.when(Runtime.getRuntime()).thenReturn(mockedRuntime);

    startProgram("doesnt matter");
}

Then, in the test, calling Runtime.getRuntime () does not bring the layout and that an IOException is thrown because String is not a directory ...

+5
2

, , , . @PrepareForTest(Runtime.class), @PrepareForTest(MyClass.class) ( MyClass , ), Runtime - . .

+4

- Runtime, .

public class AppShell {
  public Process exec(String command) {
    return Runtime.getRuntime().exec(command);
  }
}

@PrepareForTest(AppShell.class) @PrepareForTest(Runtime.class)

@RunWith(PowerMockRunner.class)
@PrepareForTest(AppShell.class)
public class AppShellTest {

    @Mock private Runtime mockRuntime;

    @Test
    public void test() {
        PowerMockito.mockStatic(Runtime.class);

        when(Runtime.getRuntime()).thenReturn(mockRuntime);
        when(mockRuntime.exec()).thenReturn("whatever you want");

        // do the rest of your test
    }
}

. PowerMock - Mocking

0

Source: https://habr.com/ru/post/1543211/


All Articles