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

发表于:2015-8-13 10:15

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:shanJX    来源:51Testing软件测试网采编

  实例代码目录结构:
  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 }
  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 }
  执行结果,"failure Trace"报错或运行失败原因:
  (1)squareRoot超时,报错
  (2)testSubstract用例失败
  (3)testMultiply忽略运行
  执行单个用例:
  选中用例,右键点击“Run”
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号