I have a Java method that starts a Process with a ProcessBuilder and translates its output into a byte array, and then returns its byte array when the process is complete.
Pseudo Code:
ProcessBuilder b = new ProcessBuilder("my.exe") Process p = b.start(); ... // get output from process, close process
What would be the best way to unit test this method? I have not found a way to mock ProcessBuilder (final), even with the incredibly awesome JMockit , it gives me a NoClassDefFoundError:
java.lang.NoClassDefFoundError: test/MockProcessBuilder at java.lang.ProcessBuilder.<init>(ProcessBuilder.java) at mypackage.MyProcess.start(ReportReaderWrapperImpl.java:97) at test.MyProcessTest.testStart(ReportReaderWrapperImplTest.java:28)
Any thoughts?
The answer . As Olaf recommended, I ended up refactoring these lines with an interface
Process start(String param) throws IOException;
Now I am passing an instance of this interface to the class that I wanted to test (in its constructor), usually using the default implementation with the source strings. When I want to test, I just use the mock interface implementation. It works like a charm, although I really wonder if I messed up here ...
java unit-testing mocking jmockit
Epaga
source share