简体   繁体   中英

JUnit4: Can't run test cases inside a JAR with lib directory outside it

My task is simple: run JUnit4 tests from terminal, with my Java classes into a JAR file and its dependencies in a directory outside that JAR ( lib/ ). I'm using Maven and the Maven Assembly plugin for that.

I run the tests with JUnitCore class, for example, this is in my main() method from example.Main class:

JUnitCore.runClasses(example.mypackage.MyClass.class);

The problem is when I run the JAR file with java -cp my-jar-file.jar example.Main -someArguments , then I get this error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/junit/runner/JUnitCore
        at example.Main.main(Main.java:21)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.JUnitCore
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

My directory tree is (note that the JUnit dependency, junit-4.11.jar , is outside the JAR):

.
├── my-jar-file.jar
└── lib
    ├── commons-beanutils-1.8.0.jar
    ├── commons-codec-1.10.jar
    ├── commons-collections-3.2.1.jar
    ├── commons-io-2.4.jar
    ├── commons-lang-2.5.jar
    ├── commons-lang3-3.4.jar
    ├── commons-logging-1.1.1.jar
    ├── cssparser-0.9.16.jar
    ├── ezmorph-1.0.6.jar
    ├── hamcrest-core-1.3.jar
    ├── htmlunit-2.18.jar
    ├── htmlunit-core-js-2.17.jar
    ├── httpclient-4.5.jar
    ├── httpcore-4.4.1.jar
    ├── httpmime-4.5.jar
    ├── jcl-over-slf4j-1.6.6.jar
    ├── jetty-io-9.2.12.v20150709.jar
    ├── jetty-util-9.2.12.v20150709.jar
    ├── json-lib-2.4-jdk15.jar
    ├── junit-4.11.jar
    ├── jwebunit-core-3.3.jar
    ├── jwebunit-htmlunit-plugin-3.3.jar
    ├── log4j-1.2.17.jar
    ├── mysql-connector-java-5.1.6.jar
    ├── nekohtml-1.9.22.jar
    ├── regexp-1.3.jar
    ├── sac-1.3.jar
    ├── serializer-2.7.2.jar
    ├── servlet-api-2.5.jar
    ├── slf4j-api-1.7.5.jar
    ├── slf4j-log4j12-1.7.5.jar
    ├── websocket-api-9.2.12.v20150709.jar
    ├── websocket-client-9.2.12.v20150709.jar
    ├── websocket-common-9.2.12.v20150709.jar
    ├── xalan-2.7.2.jar
    ├── xercesImpl-2.11.0.jar
    └── xml-apis-1.4.01.jar

Is this an issue of JUnit4? Or I'm doing something wrong?

Thanks!

You need to explicitly add the contents of lib to the classpath. Try

java -cp my-jar-file.jar:lib/\* example.Main -someArguments

if you are on unix. On windows replace : with ; and possibly remove the \\ before * ; Check the docs for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM