You have to reorganize. Extract Runtime.getRuntime().exec()
into a separate class:
public class Shell { public Process exec(String command) { return Runtime.getRuntime().exec(command); } }
Now, when you call getRuntime()
, we explicitly add the Shell
class somehow to your tested class:
public class Foo { private final Shell shell; public Foo(Shell shell) { this.shell = shell; }
In a JUnit test, just inject a cool Shell
class by passing it to the constructor:
@Mock private Shell shellMock; new Foo(shellMock);
Sidenote: yes, I'm not creating a Shell
interface with one implementation. Do not you mind? Mokito - no. Bonus: now you can check if the correct process has been called:
verify(shellMock).exec("/usr/bin/gimp");
source share