[英]Compile and run test with JUnit in command line on a single Java class
我有一個簡單的問題,我不知道如何解決!
我有一個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:我已經安裝了junit和apt install junit
,並安裝了junit-3-8-2
版本。
注3:我在嘗試編譯測試類時遇到問題,我甚至沒有達到可以運行測試的階段!
在評論部分進行了大量的試驗和錯誤后,根本原因是舊的JUnit 3.8.2依賴。 3.x版本使用了在4.x中更改為org.junit
的不同命名空間。
因此編譯測試時找不到的類。
要調試這些問題,在Linux上解壓縮jar unzip
可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.