views:

26

answers:

2

I work on a complex, multi-module maven project. One of the modules is an executable jar that implements a command-line application. I need to integration test this application. I need to run it several times, with several different command-lines and validate the exit status and stdout/err. However, I can't find a plugin for maven that claims to support this, and also can't track down a JUnit library that supports testing command-line applications.

Before you say 'don't test the main method - instead do bla', in this case I really do mean to test the main method, not some subsidiary functionality. The whole point is to run the application as a user would in its own VM and environment, and validate that it is behaving itself - parsing command-line options correctly, exiting with the write status and hot-loading the right classes from the right plugin jars.

A: 

Why not simply use a shell script, using the maven-exec-plugin to build your classpath?

STDOUT=$(mvn exec:java -DmainClass=yourMainClass --arg1 --arg2=value2)
RETURN_CODE=$?

# validate STDOUT
# validate RETURN_CODE

You can even use something like shunit2 if you prefer a more structured approach.

Robert Munteanu
The problem with this is that it is platform-specific. I realise that anything to do with running command-line apps will have some stuff that only works on windows or linux or whatever, but scripting the test in sh is probably going a step too far.
+1  A: 

My current hack is to use apache-exec from within a junit test method. It appears to be working, but is quite fiddly to set up.

public void testCommandlineApp()
        throws IOException
{
    CommandLine cl = new CommandLine(resolveScriptNameForOS("./runme")); // add .sh/.bat
    cl.addArgument("inputFile.xml");

    exec.setWorkingDirectory(workingDir);
    exec.setExitValues(new int[] { 0, 1, 2 });

    int exitCode = exec.execute(cl);

    assertEquals("Exit code should be zero", 0, exitCode);
}
You could also use the standard ProcessBuilder class, but yes, it's fiddly. (Factor out some of the more fiddly bits…)
Donal Fellows