how to use junit from the terminal

2019-08-04 08:38发布

问题:

I am trying to use junit in the terminal. I have a class Abc.java

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

and i have created a class 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);
    }
}

when i am running the command

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

I am getting the following error output

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

I tried to build the project with the command

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

it build up properly, but running this command

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

throws the following error

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

回答1:

You need to add current directory (or the directory where the compile class file are) along with the necessary jar files to class path.

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

FYI When I tried to run the same test case I used (jar files and class files in current directory)

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

And had to modify the AbcTest.java as

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);
    }
}

Changes:

  1. public class AbcTest
  2. @Test annotation for testAdd method


回答2:

JUnit's own Get Started page is a detailed How-To for running JUnit from the command-line.