Eclipse IDE 集成了JUnit开源单元测试框架。如果不借助Eclipse的图形界面工具来生成并运行我们的JUnit测试,该怎么实现呢?
1. 首先需要在类路径下添加JUnit-4.X jar 包。
2. 编写需要测试的方法。
public class Calculator { private Calculator(){} public static int add(int x, int y) { return x + y; // 正确 } public static int subtract(int x,int y) { return y - x; // 错误 } public static int multiply(int x, int y) { throw new RuntimeException(); // 抛出异常 } public static int divide(int x, int y) { return x / y; // divided by 0 } public static int module(int x , int y) { for(;;); //死循环 }}
编写测试类(Test Class)
import static org.junit.Assert.*;import org.junit.After;import org.junit.Before;import org.junit.Test;import static org.zjut.junit.Calculator.*;public class CalculatorTest { @Before public void setUp() throws Exception { System.out.println("Before testing"); } @After public void tearDown() throws Exception { System.out.println("After testing"); } @Test public void testAdd() { assertEquals("add", 3, add(1, 2)); } @Test public void testSubtract() { assertEquals("subtract", 3, subtract(5, 2)); } @Test public void testMultiply() { assertEquals("multiply", 9, multiply(3, 3)); } @Test(expected = ArithmeticException.class) public void testDivide() { divide(3, 0); } @Test(timeout=200) public void testModule() { module(1, 2); }}
运行该类:
public class Main { public static void main(String[] args) { Result result = JUnitCore.runClasses(CalculatorTest.class); for(Failure failure : result.getFailures()) { System.out.println(failure.getMessage()); //System.out.println(failure.getTrace()); //System.out.println(failure.getException()); //System.out.println(failure.getDescription()); } }}
打印语句:
Before testingAfter testingBefore testingAfter testingBefore testingAfter testingBefore testingAfter testingBefore testingAfter testingsubtract expected:<3> but was:<-3>nulltest timed out after 200 milliseconds