JUnit Test

这篇文章主要将要介绍JUnit测试工具的使用。本文中待测试的对象为一个简单的Calculate类,包括加(add),减(substract),乘(multiply),除(divide)四个简单的方法。

 1 public class Calculate {
 2     
 3     public static int add (int a, int b) {
 4         return a+b;
 5     }
 6     
 7     public static int substract (int a, int b) {
 8         return a-b;
 9     }
10     
11      public static int multiply (int a, int b) {
12          return a*b;
13      }
14      
15      public static float divide(int a, int b) {
16          return ((float)a)/((float)b);
17      }
18      
19 }

下面我们来新建一个JUnit测试类:右击Calculate.java 类,选择New-> JUnit Test Case

弹出的对话框中,点击Next继续

勾选要测试的方法,这里我们勾选全部四个方法

Eclipse会自动生成测试方法的模板,我们这里只需要补充内容即可。我们这里的测试用例如下:

表1:Add()方法的测试用例
用例编号 左操作数a 右操作数b
1 -1 1
2 1 1
3 0 1
4 Integer.MIN_VALUE 1
5 Integer.MAX_VALUE 1
表2:Substract()方法的测试用例
用例编号 左操作数a 右操作数b
1 -1 1
2 1 1
3 0 1
4 Integer.MIN_VALUE 1
5 Integer.MAX_VALUE 1
表3:Multiply()方法的测试用例
用例编号 左操作数a 右操作数b
1 -1 -1
2 1 -1
3 0 -1
4 Integer.MIN_VALUE -1
5 Integer.MAX_VALUE -1
表4:Divide()方法的测试用例
用例编号 左操作数a 右操作数b
1 -1 -2
2 1 -2
3 0 -2
4 Integer.MIN_VALUE -2
5 Integer.MAX_VALUE -2

根据上述测试用例,编写的测试用例程序如下,

 1 import static org.junit.Assert.*;
 2 import org.junit.Test;
 3 
 4 public class CalculateTest {
 5 
 6     int[] a = {-1, 1, 0, Integer.MIN_VALUE, Integer.MAX_VALUE};
 7     int[] b = {1, 1, -1, -2};
 8      
 9     @Test
10     public void testAdd() {
11         for (int i = 0; i< 5; i++) {
12             assertEquals((long)a[i]+b[0], Calculate.add(a[i], b[0]));
13         }
14     }
15 
16     @Test
17     public void testSubstract() {
18         for (int i = 0; i< 5; i++) {
19             assertEquals((long)a[i]-b[1], Calculate.substract(a[i], b[1]));
20         }
21     }
22 
23     @Test
24     public void testMultiply() {
25         for (int i = 0; i< 5; i++) {
26             assertEquals((long)a[i]*b[2], Calculate.multiply(a[i], b[2]));
27         }
28     }
29 
30     @Test
31     public void testDivide() {
32         for (int i = 0; i< 5; i++) {
33             assertEquals((double)a[i]/b[3], Calculate.divide(a[i], b[3]));
34         }
35     }
36 
37 }

右击CalculateTest.java文件,选择Run as -> JUnit Test

得到测试结果如下:

我们发现,四个方法的测试均失败了。再看下方的Failure Trace给出的提示,发现原来是计算的值超过了Int型的范围导致的溢出错误。因此我们对原程序进行更改,将操作数的类型改为long int型,再次进行测试。

这次测试四个测试用例全部通过, 说明我们的程序达到了预期的质量标准。

这次关于JUnit的介绍到此就结束了,本文中的代码已发布至GitHub(https://github.com/tuhz/CalculateTest)

欢迎留言反馈。

原文地址:https://www.cnblogs.com/tuhz/p/4528807.html