How to go around Runtime.getRuntime() while writing JUnit?

java, junit, mockito, singleton, unit-testing

Solution

You must refactor. Extract `Runtime.getRuntime().exec()` into a separate class:

public class Shell {

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

}

Now insted of calling `getRuntime()` explicitly inject `Shell` class somehow to your class under test:

public class Foo {

  private final Shell shell;

  public Foo(Shell shell) {
    this.shell = shell;
  }

  //...
  shell.exec(...)

}

In JUnit test simply inject mocked `Shell` class by passing it to constructor:

@Mock
private Shell shellMock;

new Foo(shellMock);

Sidenote: yes, I am not creating a `Shell` interface with one implementation. Do you mind? Mockito is not. Bonus: you can now verify if the correct process was called:

verify(shellMock).exec("/usr/bin/gimp");

Problem

I have a class where Runtime.getRuntime() is used for executing a script from command line and getting the result for further processing. But when I write JUnit for this class, I cannot find a way to mock/avoid this Runtime.getRuntime().exec() . I cannot use EasyMock or PowerMock or any other mock api other than Mockito. Please give me a way to overcome this problem, because this is affecting the code coverage.

Original source