【发布时间】:2019-03-14 16:36:40
【问题描述】:
我有一个简单的问题我不知道如何解决!
我有一个 Java 文件 User.java:
import java.util.Vector;
public class User {
private String name;
private Vector<User> friends;
public User(String name) {
this.name = name;
this.friends = new Vector<>();
}
public void addFriend(User newfriend) {
friends.add(newfriend);
}
public boolean isFriendsWith(User friend) {
return friends.indexOf(friend) != -1;
}
}
我在这个类旁边有一个简单的测试类UserTest.java:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class UserTest {
@Test
public void evaluatesExpression() {
User user = new User("foo");
User user2 = new User("bar");
user.addFriend(user2);
assertEquals(true, user.isFriendsWith(user2));
}
}
我想为User 类运行这个测试类。
我没有使用 IntelliJ 或 Eclipse 之类的 IDE,所以我想从 linux 命令行编译测试,但是这个命令:
javac -cp .:"/usr/share/java/junit.jar" UserTest.java
给我以下错误:
UserTest.java:1: error: package org.junit does not exist
import static org.junit.Assert.assertEquals;
^
UserTest.java:1: error: static import only from classes and interfaces
import static org.junit.Assert.assertEquals;
^
UserTest.java:2: error: package org.junit does not exist
import org.junit.Test;
^
UserTest.java:6: error: cannot find symbol
@Test
^
symbol: class Test
location: class UserTest
UserTest.java:11: error: cannot find symbol
assertEquals(true, user.isFriendsWith(user2));
^
symbol: method assertEquals(boolean,boolean)
location: class UserTest
5 errors
注意:我在 Stackoverflow 上看到的所有内容都是关于测试项目中的单个文件或使用 gradle 构建和测试...,但我对 Java 不太了解,我也不知道不需要知道太多,我只需要知道为单个 Java 类创建和运行测试的最简单方法。
注意2:我用apt install junit安装了junit,它安装了junit-3-8-2版本。
注意3:我在尝试编译我的测试类时遇到问题,我什至还没有达到可以运行测试的阶段!
【问题讨论】:
-
离题,但从不使用
Vector。 -
@shmosel 谢谢,但它是给我的项目代码的一部分!
-
javac -d /absolute/path/for/compiled/classes -cp /absolute/path/to/junit-4.12.jar /absolute/path/to/TestClassName.java如上述答案所述。 -
junit-3-8-2已经过时了。它不使用 org.junit 命名空间。至少使用 4.x.. 根本原因是,您的类路径上没有org.junit.Assert,因为您使用的库是在 JUnit 团队重命名之前。但是您尝试运行的测试使用的是 4.x 代码。 mvnrepository.com/artifact/junit/junit/4.12
标签: java junit command-line