public int abs(int value) { return value>=0 ? value : (-value); }
public int div(int a, int b) { return a / b; }
/** * BUG: if b less than 0! */ public float exp(int a, int b) { float r = 1; for(int i=0; i<b; i++) r = r * a; return r; } } 注意exp()方法是有Bug的,如果传入参数2, -1,则期待的返回值应为0.5F,但实际返回值为1.0F。
下面我们看看传统的JUnit的TestCase:
public class MathTest extends TestCase {
public void setUp() { super.setUp(); } public void tearDown() { super.tearDown(); }
public void testAbs() { assertTrue(true); } public void testDiv() {...} public void testExp() {...}
public MathTest() { System.out.println("new MathTest instance."); }
@Before public void setUp() throws Exception { System.out.println("call @Before before a test method"); }
@After public void tearDown() throws Exception { System.out.println("call @After after a test method"); }
@Test public void doAbs() { Math math = new Math(); assertEquals(200, math.abs(200)); assertEquals(100, math.abs(-100)); assertEquals(0, math.abs(0)); }
@Test public void doDiv() { Math math = new Math(); assertEquals(5, math.div(100, 20)); assertEquals(4, math.div(100, 21)); }
@Test(expected=ArithmeticException.class) public void doDiv0() { new Math().div(127, 0); }
@Test(timeout=1) public void doLongTimeTask() { double d = 0; for(int i=1; i<10000000; i++) d+=i; }
@Test public void testExp() { Math math = new Math(); assertEquals(32f, math.exp(2, 5), 0.001f); assertEquals(1f, math.exp(2, 0), 0.001f); assertEquals(0.5f, math.exp(2, (-1)), 0.001f); }