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);
...
}
}
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) {
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 ...