javajunitillegalargumentexceptionclassnotfoundjunit-runner

How to run JUnit tests from the command line if classes are in packages?


The class ParserTest is in the package myproject.tests and stored in this directory structure:

.
└── myproject
    └── tests
        └── ParserTest.class

Set the CLASSPATH for the current shell session (no -cp option, to keep to java call clean):

export CLASSPATH=.:/usr/local/lib/java/junit-4.12.jar:/usr/local/lib/java/hamcrest-core-1.3.jar

Call the JUnit runner and pass the test class as the argument:

java org.junit.runner.JUnitCore myproject/tests/ParserTest

This error gets thrown:

...
1) initializationError(org.junit.runner.JUnitCommandLineParseResult)
java.lang.IllegalArgumentException: Could not find class [myproject/tests/ParserTest]
...

Solution

  • org.junit.runner.JUnitCore requires the argument to use . as a separator between directories and classes, instead of /.

    The calltrace looks like that and ends in java.lang.Class.forName(classname):

    JUnitCore.main(args)
    └── JUnitCore.runMain(args)
        └── JUnitCommandLineParseResult.parse(args)
            └── new JUnitCommandLineParseResult().parseArgs(args);
                └── JUnitCommandLineParseResult.parseParameters(...);
                    └── ...
                        └── org.junit.internal.Classes.getClass(arg);
                            └── java.lang.Class.forName(className);
    

    The JavaDoc for java.lang.Class.forName(String className) says:

    Parameters: className - the fully qualified name of the desired class.

    And in Java, fully qualified names are written with . not /.