eclipse JUnit Unit test

Install JUnit

  1. Download junit-4.10.jar from http://sourceforge.net/projects/junit/files/junit/4.10/ to workspace/your-project/lib/
  2. start eclipse
  3. select your-project top node
  4. right click
  5. select [Refresh]
  6. select your-project top node
  7. right click
  8. select [Property]
  9. select [Java Build Path]
  10. select [Libraries] tab
  11. click [add JARs]
  12. select lib/junit-4.10.jar
  13. click [OK]

generate unit-test

  1. select your class(want test)
  2. right click
  3. [New] -> [JUnit test case]
  4. [Finish]

run unit-test

  1. right click generated (edited) unit-test class
  2. [run as] -> [JUnit Test]

unit-test example

test this class

public class ChangeNum {
  public static void main(String[] args) {
    ChangeNum cn1 = new ChangeNum();
    cn1.changeNum(args[0]);
  }

  int changeNum(String s1) {
    int n1 = Integer.parseInt(s1);
    return n1;
  }
}
  1. select this class
  2. right click
  3. [New] -> [JUnit test case]
  4. [Finish]
  5. edit generated file as:
import junit.framework.TestCase;

public class ChangeNumTest extends TestCase {
  public ChangeNumTest(String name) {
    super(name);
  }
 
  public void testChangeNum() {
    String ts1 = "100"; 
    int tn1 = 100;
    ChangeNum tcn1 = new ChangeNum(); 
    int test1 = tcn1.changeNum(ts1); 
    assertEquals("Error not number type", tn1, test1); 
  }
}
  1. right click ChangeNumTest class
  2. [run as] -> [JUnit Test]

run all unit-test

  1. select your packege
  2. right click
  3. [new]->[other]->[java]->[JUnit]->[JUnit Test Suite]->[Next]
  4. click [select All]
  5. click [Finish]