Question: 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.

Answer: 
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");

```
I used sub-classing and overriding (as explained in Michael C. Feathers' book "Working effectively with legacy code")

Suppose we have the following code:

```
public class CannotChange{
    public CannotChange(){}
    public void TryingToTest() throws IOException {
        ...
        Process proc = Runtime.getRuntime().exec("command");
        ...
    }
}

```

Extract the runtime code into a protected method:

```
    public void TryingToTest() throws IOException {
        ...
        Process proc = execute("command");
        ...
    }
    protected Process execute(string command){ 
        return Runtime.getRuntime().exec(command);
    }     

```

Then in the test class create a class that extends CannotChange class and overrides 
execute

```
public class CannotChangeTest{

   private class CannotChangeForTesting extends CannotChange{
      public CannotChangeForTesting(){ super(); }
      @Override
      public Process execute(String command){
         return null; //or a mocked object
      }
   }

   @Test
   public void TestMethod(){
      CannotChange cannotChange = new ForTestCannotChange();
      cannotChange.TryingToTest();
   }
}

```