1.æ–°å¾java工程testJunit3 , æ–°å¾åŒ…å’Œ¾c»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("除数ä¸èƒ½ä¸ºé›¶åQ?/span>");
15 }
16
17 return a / b;
18 }
19
20 }
21
‹¹‹è¯•¾c»ï¼š(x¨¬)
1 package com.test.junit3;
2
3 import junit.framework.Assert;
4 import junit.framework.TestCase;
5
6 /**
7 * 在junit3.8䏿µ‹è¯•类必需¾l§æ‰¿TestCase父类
8 *
9 */
10 public class CalculatorTest extends TestCase{
11
12 /**
13 * 在junit3.8ä¸?‹¹‹è¯•æ–ÒŽ(gu¨©)³•满èƒö如下原则
14 * 1) public
15 * 2) void
16 * 3) æ— æ–¹æ³•å‚æ•?br />
17 * 4) æ–ÒŽ(gu¨©)³•å称必须以testå¼€å¤?br />
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(); //æ–言å¤ÞpÓ|
38 }
39 catch(Exception ex)
40 {
41 tx = ex;
42 }
43
44 Assert.assertNotNull(tx); //æ–言ä¸äØ“(f¨´)½I?/span>
45
46 Assert.assertEquals(Exception.class,tx.getClass());//æ–言¾cÕdž‹ç›¸åŒ
47
48 Assert.assertEquals("除数ä¸èƒ½ä¸ºé›¶åQ?/span>",tx.getMessage());//æ–言消æ¯ç›¸åŒ
49 }
50 }
51
3. ˜q行¾l“æžœ


]]>