實(shí)例代碼目錄結(jié)構(gòu):
Calculator.java:
1 public class Calculator{
2 private static int result;//靜態(tài)變量,用于存儲運(yùn)行結(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"報錯或運(yùn)行失敗原因:
。1)squareRoot超時,報錯
。2)testSubstract用例失敗
。3)testMultiply忽略運(yùn)行
執(zhí)行單個用例:
選中用例,右鍵點(diǎn)擊“Run”