Junit参数化

数据驱动测试:测试代码要与测试数据分离

哎~~学习时发现一个问题,写完了测试文件,右击文件时没有run as -》junit test的选项,找了好半天,终于知道了原因,是方法前没有加static关键字!!!太尼玛坑爹了!

被测方法:

public class JunitDemo {
public int add(int x,int y){
return x+y;
}
public int subtraction(int x,int y){
return x-y;
}

}

Junit测试文件:

package day101.junitTest;

import static org.junit.Assert.assertEquals;

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

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

import day101.junit.JunitDemo;

public static class JunitDemoTest {
/**
* 参数化测试的类必须有Parameterized测试运行器修饰
*
*/

@RunWith(Parameterized.class)
public class AddTest{
private int a;
private int b;
private int expected;

  1.  /** 
  2.      * 准备数据。数据的准备需要在一个方法中进行,该方法需要满足一定的要求: 
  3.  
  4.          1)该方法必须由Parameters注解修饰 
  5.          2)该方法必须为public static的 
  6.          3)该方法必须返回Collection类型 
  7.          4)该方法的名字不做要求 
  8.          5)该方法没有参数 
  9.      * @return 
  10.      */ 


@Parameters
@SuppressWarnings("unchecked")
public static Collection<Object[]> prepareData(){
Object[][] object ={{0,0,0},{1,1,2},{2,2,4}};
return Arrays.asList(object);
}

public AddTest(int a,int b,int expected){
this.a = a;
this.b = b;
this.expected = expected;
}

@Test
public void testAdd(){
JunitDemo add = new JunitDemo();
int result = add.add(a, b);
Assert.assertEquals(expected, result);
}

}
}

原文地址:https://www.cnblogs.com/sylovezp/p/4126193.html