How to unit test Java methods using processbuilder and process?
I have a Java method that starts a process with processbuilder, outputs its output pipeline to a byte array, and then returns its byte array after the process is completed
Pseudo code:
ProcessBuilder b = new ProcessBuilder("my.exe") Process p = b.start(); ... // get output from process,close process
What is the best way to unit test this approach? I haven't found a way to simulate processbuilder (it's final). Even the great jmockit 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 ideas?
Answer – as Olaf recommends, I eventually refactor these lines into interfaces
Process start(String param) throws IOException;
I now pass an instance of this interface to the class I want to test (in its constructor), usually using the default implementation with the original line When I want to test, I only need to use the simulated implementation of the interface Like charm, although I wonder if I'm over interfacing here
Solution
A course to protect yourself from ridicule Create an interface to perform what you really want (for example, hide the fact that the external process is completely involved) or only for process and processbuilder
You don't want testing, process builder and process to work, just you can use their output When you create an interface, a simple implementation (which can be easily checked) delegates to processbuilder and process, and another implementation simulates this behavior Later you can even use another implementation to do what you need without starting another process