title: How do I unit test a Java method which uses ProcessBuilder and Process?
body: <p>I have a Java method which starts up a Process with ProcessBuilder, and pipes its output into a byte array, and then returns its byte array when the process is finished.</p>
  
  <p>Pseudo-code:</p>
  
  <pre><code>ProcessBuilder b = new ProcessBuilder("my.exe")
  Process p = b.start();
  ... // get output from process, close process
  </code></pre>
  
  <p>What would be the best way to go about unit testing this method? I haven't found a way to mock ProcessBuilder (it's final), even with the incredibly awesome <a href="http://jmockit.org" rel="noreferrer">JMockit</a>, it gives me a NoClassDefFoundError:</p>
  
  <pre><code>java.lang.NoClassDefFoundError: test/MockProcessBuilder
      at java.lang.ProcessBuilder.&lt;init&gt;(ProcessBuilder.java)
      at mypackage.MyProcess.start(ReportReaderWrapperImpl.java:97)
      at test.MyProcessTest.testStart(ReportReaderWrapperImplTest.java:28)
  </code></pre>
  
  <p>Any thoughts?</p>
  
  <hr>
  
  <p><strong>Answer</strong> - As Olaf recommended, I ended up refactoring those lines to an interface</p>
  
  <pre><code>Process start(String param) throws IOException;
  </code></pre>
  
  <p>I now pass an instance of this interface into the class I wanted to test (in its constructor), normally using a default implementation with the original lines. When I want to test I simply use a mock implementation of the interface. Works like a charm, though I do wonder if I'm over-interfacing here...</p>