当前位置: 代码迷 >> java >> 如何从终端使用junit
  详细解决方案

如何从终端使用junit

热度:33   发布时间:2023-08-02 10:42:22.0

我正在尝试在终端中使用junit。 我有一个Abc.java类

class Abc{
    public int add(int a, int b){
         return a+b
    }
}

我创建了一个类AbcTest.java

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

class AbcTest {
    public void testAdd() {
        System.out.println("add");
        int a = 0;
        int b = 0;
        Abc instance = new Abc();
        int expResult = 0;
        int result = instance.add(a, b);
        assertEquals(expResult, result);
    }
}

当我运行命令时

javac -cp /usr/share/java/junit4.jar AbcTest.java

我收到以下错误输出

AbcTest.java:16: error: cannot find symbol
Abc instance = new Abc();
^
symbol:   class Abc
location: class AbcTest
AbcTest.java:16: error: cannot find symbol
Abc instance = new Abc();
                   ^
symbol:   class Abc
location: class AbcTest
2 errors

我尝试使用命令构建项目

javac -cp /usr/share/java/junit4.jar *.java

它可以正确建立,但是运行此命令

java -cp /usr/share/java/junit4.jar org.junit.runner.JUnitCore AbcTest

引发以下错误

JUnit version 4.11
Could not find class: AbcTest
Time: 0.002
OK (0 tests)

您需要将当前目录(或编译类文件所在的目录)以及必要的jar文件添加到类路径。

java -cp /usr/share/java/junit4.jar:. org.junit.runner.JUnitCore AbcTest

仅供参考,当我尝试运行相同的测试用例时(当前目录中的jar文件和类文件)

javac -cp junit-4.11.jar:. AbcTest.java
java -cp junit-4.11.jar:hamcrest-core-1.3.jar:. org.junit.runner.JUnitCore AbcTest

并且不得不将AbcTest.java修改为

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;


public class AbcTest {
    @Test
    public void testAdd() {
        System.out.println("add");
        int a = 0;
        int b = 0;
        Abc instance = new Abc();
        int expResult = 0;
        int result = instance.add(a, b);
        assertEquals(expResult, result);
    }
}

变化:

  1. 公共课程AbcTest
  2. @Test注释为testAdd方法

JUnit自己的是从命令行运行JUnit的详细操作方法。

  相关解决方案