junit参数化测试的使用方法

JUnit参数化测试的五个步骤:
(1)为准备使用参数化测试的测试类指定特殊的运行器 org.junit.runners.Parameterized。
(2)为测试类声明几个变量,分别用于存放期望值和测试所用数据。
(3)为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。
(4)为测试类声明一个使用注解 org.junit.runners.Parameterized.Parameters 修饰的,返回值为 java.util.Collection 的公共静态方法,并在此方法中初始化所有需要测试的参数对。
(5)编写测试方法,使用定义的变量作为参数进行测试。

import static org.junit.Assert.assertEquals;

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

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

//(1)步骤一:测试类指定特殊的运行器org.junit.runners.Parameterized ,表示该类将不使用Junit内建的运行器运行,而使用参数化运行器运行
@RunWith(Parameterized.class)
public class CalculatorTest {
    private Calculator cal;
    
    // (2)步骤二:为测试类声明几个变量,分别用于存放期望值和测试所用数据。  
    private int expected;
    private int input1;
    private int input2;

    @Before
    public void setUp() {
        cal = new Calculator();
    }



    // (3)步骤三:为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。
    public CalculatorTest(int expected, int input1, int input2)// 构造方法,为各个参数赋值。
    {
        this.expected = expected;
        this.input1 = input1;
        this.input2 = input2;
    }
    
    // (4)步骤四:为测试类声明一个使用注解 org.junit.runners.Parameterized.Parameters 修饰的,返回值为  
    // java.util.Collection 的公共静态方法,并在此方法中初始化所有需要测试的参数对。  
    @Parameters
    public static Collection<Integer[]> prepareData() {
        Integer[][] object = { { 3, 1, 2 }, { -4, -1, -3 }, { 5, 0, 5 } };
        return Arrays.asList(object);// 数组转化成集合形式。
    }

    // (5)步骤五:编写测试方法,使用定义的变量作为参数进行测试。  
    @Test
    public void testAdd() {
        System.out.println(this.input1+","+this.input2);
        assertEquals(this.expected, cal.add(this.input1, this.input2));// 注意是调用的成员变量。
    }
    
    
}
output:
1,2
-1,-3
0,5

http://blog.csdn.net/seven_3306/article/details/8069948

在Junit中,如果想要同时运行多个测试,需要使用两个注解,
@RunWith(Suite.class)和
@Suite.SuiteClasses(),

创建一个空类作为测试套件的入口。
使用注解 org.junit.runner.RunWith 和 org.junit.runners.Suite.SuiteClasses 修饰这个空类。

通过这两个注解分别指定使用Suite运行器来运行测试,以及指定了运行哪些测试类,其中的,@RunWith(Suite.class)中可以继续指定Suite,这样Junit会再去寻找里面的测试类,一直找到能够执行的TestCase并执行之。

将 org.junit.runners.Suite 作为参数传入注解 RunWith,以提示 JUnit 为此类使用套件运行器执行。
将需要放入此测试套件的测试类组成数组作为注解 SuiteClasses 的参数。
保证这个空类使用 public 修饰,而且存在公开的不带有任何参数的构造函数

package com.shengsiyuan.junit;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({CalculatorTest.class,ParametersTest.class})

public class TestAll {//仅仅一个摆设,实际没用。

}


@BeforeClass、@AfterClass在所有的测试方法以及。@Before、@After执行之前执行。仅仅执行一次,相当于全局初始化和全局销毁,而@Before、@After有多少测试方法就执行多少次



@Ignore可以修饰忽略一个已被@Test修饰的测试方法,也可以修饰一个类,那么类下的所有方法都会被忽略。还可带一个可选的默认参数,用于说明原因。



http://blog.sina.com.cn/s/blog_5cd7f5b40100smao.html




原文地址:https://www.cnblogs.com/softidea/p/4155312.html