1.新建java工程testJunit3 , 新建包和類Calculator和CalculatorTest

2.編寫代碼
1 package com.test.junit3;
2
3 public class Calculator {
4
5
6 public int add(int a,int b){
7 return a + b ;
8 }
9
10 public int divide(int a, int b) throws Exception
11 {
12 if(0 == b)
13 {
14 throw new Exception("除數不能為零!");
15 }
16
17 return a / b;
18 }
19
20 }
21
測試類:
1 package com.test.junit3;
2
3 import junit.framework.Assert;
4 import junit.framework.TestCase;
5
6 /**
7 * 在junit3.8中測試類必需繼承TestCase父類
8 *
9 */
10 public class CalculatorTest extends TestCase{
11
12 /**
13 * 在junit3.8中,測試方法滿足如下原則
14 * 1) public
15 * 2) void
16 * 3) 無方法參數
17 * 4) 方法名稱必須以test開頭
18 */
19 public void testAdd(){
20
21 Calculator cal = new Calculator();
22
23 int result = cal.add(1, 2);
24
25 Assert.assertEquals(3, result);;
26 }
27
28 public void testDivide(){
29 Throwable tx = null;
30
31 try
32 {
33 Calculator cal = new Calculator();
34
35 cal.divide(4,0);
36
37 Assert.fail(); //斷言失敗
38 }
39 catch(Exception ex)
40 {
41 tx = ex;
42 }
43
44 Assert.assertNotNull(tx); //斷言不為空
45
46 Assert.assertEquals(Exception.class,tx.getClass());//斷言類型相同
47
48 Assert.assertEquals("除數不能為零!",tx.getMessage());//斷言消息相同
49 }
50 }
51
3. 運行結果
