junit基础篇、中级篇实例代码

学习文章:

http://blog.csdn.net/andycpp/article/details/1327147

http://wenku.baidu.com/link?url=C27gDEj0l-AyPuyUOOYJaezxGF-U-mozQbjlA-R9apKXdw8h-GV3VoPzS4P4WADISon7615JCLfSpMjtuiqIVcBWJ0o7icgKk_2Qi2jF0yq

实例代码目录结构:

Calculator.java:

 1 public class Calculator{
 2     private static int result;//静态变量,用于存储运行结果
 3     
 4     public void add(int n){
 5         result = result+n;
 6     }
 7     
 8     public void substract(int n){
 9         result = result-1;//bug:之前应该是 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:死循环
26     }
27     
28     public void clear(){
29         result = 0;
30     }
31     
32     public int getResult(){
33         return result;
34     }
35 }
View Code

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 }
View Code

执行结果,"failure Trace"报错或运行失败原因:

(1)squareRoot超时,报错

(2)testSubstract用例失败

(3)testMultiply忽略运行

执行单个用例:

选中用例,右键点击“Run”

原文地址:https://www.cnblogs.com/shanJX/p/4720443.html