下面是一個簡單的計算機程式
Calculator.javalink1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.zjw.junit4;
public class Calculator {
public int plus(int x, int y) { return x + y; }
public int subtraction(int x, int y) { return x - y; }
public int multiplication(int x, int y) { return x * y; }
public int division(int x, int y) { return x / y; }
}
|
測試程式
TestCalculator.javalink1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.zjw.junit4.test;
import static org.junit.Assert.*;
import org.junit.Ignore; import org.junit.Test;
import com.zjw.junit4.Calculator;
public class TestCalculator {
@Test public void testPlus() { Calculator cal = new Calculator(); assertEquals(cal.plus(5, 5), 10); }
@Test public void testSubtraction() { Calculator cal = new Calculator(); assertEquals(cal.subtraction(5, 5), 0); }
@Ignore @Test public void testMultiplication() { Calculator cal = new Calculator(); assertTrue(cal.multiplication(5, 5) > 20); }
@Test(expected = java.lang.ArithmeticException.class, timeout = 50) public void testDivision() { Calculator cal = new Calculator(); assertEquals(cal.division(8, 0), 4); } }
|
// @Test expected后面指定你希望抛出的异常,timeout的意思是 如果测试没有在50ms内完成,那么就算测试失败.
@Test(expected = java.lang.ArithmeticException.class, timeout = 50)
JUnit的Annoation:
- @Test: 测试方法
a. (expected=XXException.class)
b. (timeout=xxx)
- @Ignore: 忽略测试方法
- @Before: 每一个测试方法之前运行
- @After: 每一个测试方法之后运行
- @BeforeClass: 所有测试开始之前运行,别忘了方法是静态的.
- @AfterClass: 所有测试结束之后运行
Source :