Junit4学习(六)Junit4参数化设置

一,背景,

有时候会对相同的代码结构做同样的操作,不同的时对参数的设置数据和预期结果;有没有好的办法提取出来相同的代码,提高代码的可重用度,junit4中使用参数化设置,来处理此种场景;

二,代码展示,

1,右键test/com.duo.util新建->junit Test Case

2,修改测试运行器(@RunWith(Parameterized.class))

 1 package com.duo.util;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.junit.runners.Parameterized;
 8 
 9 
10 @RunWith(Parameterized.class)
11 public class ParameterTest {
12 
13     
14 }

3,声明变量存储测试数据和预期值

4,测试多组数据,就需要声明一个数组存放结果数据;为测试类声明返回值为Collection公共静态方法;

 1 package com.duo.util;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import java.util.Arrays;
 6 import java.util.Collection;
 7 
 8 import org.junit.Test;
 9 import org.junit.runner.RunWith;
10 import org.junit.runners.Parameterized;
11 import org.junit.runners.Parameterized.Parameters;
12 
13 
14 @RunWith(Parameterized.class)
15 public class ParameterTest {
16     int expected = 0;
17     int input1 = 0;
18     int input2 = 0;
19     
20     @Parameters
21     public static Collection<Object[]> t(){
22         return Arrays.asList(new Object[][]{{3,1,2},{4,2,2}});
23     }
24     
25     public ParameterTest(int expected, int input1, int input2){
26         this.expected = expected;
27         this.input1 = input1;
28         this.input2 = input2;
29     }
30     
31     @Test
32     public void testAdd(){
33         assertEquals(expected, new Calculate().add(input1, input2));
34     }
35 
36     
37 }

 三,总结

1,更改默认的测试运行器为RunWith(Parameterized.class)

2,声明变量存储预期值和测试数据

3,声明一个返回值为Collection公共静态方法,并使用@Parameters进行修饰

4,为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值

原文地址:https://www.cnblogs.com/august-shi/p/6721364.html