---
title: "junit学习（七）——参数化设置：同时测试一组数据"
author: "wjiaoling136"
date: "2018-01-16T10:32:46Z"
tags: []
categories: ["编程语言"]
slug: "junit"
draft: false
lastmod: "2018-01-16T10:32:45Z"
id: 2407804
url: "https://1017401036.iteye.com/blog/2407804"
---

如何同时测试一组数据？？看代码吧，代码里边有详细的步骤说明：

```
package com.wjl.junit;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Junit_demo_10
 * JUnit参数化设置：同时测试一组数据
 * **/
//1、更改默认的测试运行器为@RunWith(Parameterized.class)
@RunWith(Parameterized.class)
public class ParameterTest {
	//2、声明变量用来存放预期值和输入值
	int expected = 0;//预期值
	int input1 = 0;//输入值1
	int input2 = 0;//输入值2
	
	//3、声明一个返回值为Collection的公共静态方法，并使用@Parameters进行修改
	@Parameters
	public static Collection<Object[]> t(){
		return Arrays.asList(new Object[][]{
				{3,1,2},
				{4,2,2},
				{2,2,0}
		});
	}
	
	//4、为测试类声明一个带有参数的公共构造方法，并在其中为变量赋值
	public ParameterTest(int expected,int input1,int input2){
		this.expected = expected;
		this.input1 = input1;
		this.input2 = input2;
	}
	
	//5、添加测试方法进行测试
	@Test
	public void test(){
		assertEquals(expected,new Calculate().add(input1,input2));
	}
}
```

运行结果如下：  
![](http://dl2.iteye.com/upload/attachment/0128/5500/8423d158-158e-3706-8c9e-1a605596261b.png)