【问题标题】:Compile and run test with JUnit in command line on a single Java class在单个 Java 类的命令行中使用 JUnit 编译和运行测试
【发布时间】: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


【解决方案1】:

在 cmets 部分经过大量试验和错误后,根本原因是旧的 JUnit 3.8.2 依赖项。 3.x 版本使用了不同的命名空间,在 4.x 中更改为 org.junit

因此编译测试时找不到的类。

要调试此类问题,在 Linux 上使用 unzip 解压缩 jar 会很有帮助。

【讨论】:

  • 在 Windows 上将 .jar 重命名为 .zip 并打开它。应该可以在没有安装任何其他软件的情况下工作。我们使用这种技术来检查战争(也只是 zip 文件)
猜你喜欢
  • 2012-03-06
  • 1970-01-01
  • 2016-03-22
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 2014-05-30
相关资源
最近更新 更多