您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
Junit基礎(chǔ)篇、中級篇實例代碼
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2015/8/13 11:31:33 ] 推薦標(biāo)簽:軟件測試工具 單元測試工具

  實例代碼目錄結(jié)構(gòu):

  Calculator.java:
1 public class Calculator{
2     private static int result;//靜態(tài)變量,用于存儲運行結(jié)果
3
4     public void add(int n){
5         result = result+n;
6     }
7
8     public void substract(int n){
9         result = result-1;//bug:之前應(yīng)該是 result = result-n
10     }
11
12     public void multiply(int n){
13
14     }//此方法尚未寫好
15
16     public void divide(int n){
17         result = result/n;
18     }
19
20     public void square(int n){
21         result = n*n;
22     }
23
24     public void squareRoot(int n){
25         for(;;){}  //bug:死循環(huán)
26     }
27
28     public void clear(){
29         result = 0;
30     }
31
32     public int getResult(){
33         return result;
34     }
35 }
  CalculatorTest.java:
1 import static org.junit.Assert.*;
2
3 import org.junit.After;
4 import org.junit.Before;
5 import org.junit.Ignore;
6 import org.junit.Test;
7
8
9 public class CalculatorTest {
10
11     private static Calculator calculator = new Calculator();
12
13     @Before
14     public void setUp() throws Exception {
15         calculator.clear();
16     }
17
18     @After
19     public void tearDown() throws Exception {
20     }
21
22     @Test
23     public void testAdd() {
24         calculator.add(2);
25         calculator.add(3);
26         assertEquals(5,calculator.getResult());
27     }
28
29     @Test
30     public void testSubstract() {
31         calculator.add(10);
32         calculator.substract(2);
33         assertEquals(8,calculator.getResult());
34     }
35
36     @Ignore("Multiply() Not yet implemented")
37     @Test
38     public void testMultiply() {
39
40     }
41
42     @Test
43     public void testDivide() {
44         calculator.add(8);
45         calculator.divide(2);
46         assertEquals(4,calculator.getResult());
47     }
48
49     @Test(timeout = 1000)
50     public void squareRoot(){
51         calculator.squareRoot(4);
52         assertEquals(2,calculator.getResult());
53     }
54
55     @Test(expected = ArithmeticException.class)
56     public void divideByZero(){
57         calculator.divide(0);
58     }
59 }
  執(zhí)行結(jié)果,"failure Trace"報錯或運行失敗原因:
 。1)squareRoot超時,報錯
  (2)testSubstract用例失敗
 。3)testMultiply忽略運行

  執(zhí)行單個用例:
  選中用例,右鍵點擊“Run”

軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd