开发者

How can I test command-line applications using maven?

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 corr开发者_高级运维ectly, exiting with the write status and hot-loading the right classes from the right plugin jars.


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜