java - JUnit 示例程序编译但给出运行时错误

标签 java linux junit classpath

我开始在 Ubuntu 中使用 JUnit 并尝试执行给定的示例程序 here .我也遵循了同一链接中给出的说明。代码编译成功但运行时报错如下:

Exception in thread "main" java.lang.NoClassDefFoundError: org/junit/runner/JUnitCore
    at TestRunner.main(TestRunner.java:7)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.JUnitCore
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

到目前为止,这就是我所得到的。如果 $CLASSPATH 变量未设置为其所需类的位置,则会发生此错误。

> echo $CLASSPATH
/home/webyog/workspace/JUNIT/junit-4.11.jar:.

我的 java 文件和类文件在 /home/webyog/JUNIT_WORKSPACE/ 中,所有库和 JUnit jar 文件在 /home/webyog/workspace/JUNIT/。 我按顺序执行了这些:

javac TestJunit.java TestRunner.java -classpath /home/webyog/workspace/JUNIT/junit-4.11

(这生成了 2 个文件 TestRunner.classTestJunit.class)

java TestRunner -classpath $CLASSPATH

(这给出了错误)

我错过了什么?请帮忙。

最佳答案

在你的问题中,你有 /home/webyog/workspace/JUNIT/junit-4.11.jar:. 用于 $CLASSPATH 但声明:

the JUnit jar file is in /home/webyog/JUNIT/

(注意缺少workspace)

这可以解释您看到的错误。

尝试:

cd /home/webyog/JUNIT_WORKSPACE/
java -cp '/home/webyog/JUNIT/junit-4.11.jar:.' TestRunner 

您可能还想查看一些构建工具,让您的生活更轻松(maven、ant、gradle,...)

关于java - JUnit 示例程序编译但给出运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20852689/

相关文章:

java - TestRestTemplate - 从 Spring Boot 1.5 迁移到 2.0

java - 我得到了非封闭类

python:参数列表太长

java - 为 JERSEY Web 服务编写测试用例的最佳方法是什么?

java - 如何基于Web源创建Eclipse项目

java - 使用 JavaMail 创建多部分

linux - 如何将 2 个 bash 命令与包含的 print0 结合起来

linux - 如何延迟管道 netcat 连接到第一个输入

java - 使用 JUnit 5 和 Spring Boot 2.0.0 进行嵌套测试

java - 如何在 Maven surefire 中查看逐个测试标准输出/标准错误