junit 参数化测试


参数化测试(Parameters):当一个测试类使用参数化运行器运行时,需要在类的声明处加上@RunWith(Parameterized.class)注解,表示该类将不使用Junit内建的运行器运行,而使用参数化运行器运行;在参数化运行类中提供参数的方法上要使用@Parameters注解来修饰,同时在测试类的构造方法中为各个参数赋值(构造方法是由Junit调用的),最后编写测试类,它会根据参数的组数来运行测试多次。

package com.junit.test;

public class Calcular {

    public int add(int a, int b) {
        return a + b;
    }
}

测试:

package com.junit.test;

import static org.junit.Assert.*;

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;

@RunWith(Parameterized.class)
public class CalcularAddTest {
    Calcular cal;
    private int expected;
    private int input1;
    private int input2;

    @Parameters
    public static Collection paraData() {
        Object[][] object = { { 5, 2, 3 }, { 12, 8, 4 }, { 6, 4, 2 }, { 9, 0, 9 }, { 0, 0, 0 } };
        return Arrays.asList(object);
    }

    @Before
    public void setUp() throws Exception {
        cal = new Calcular();
    }

    public CalcularAddTest(int expected, int input1, int input2) {
        this.expected = expected;

        this.input1 = input1;

        this.input2 = input2;
    }

    @Test
    public void testSub() {
        assertEquals(expected, cal.subtract(input1, input2));

    }

}
Joyce /
Published under (CC) BY-NC-SA in categories junit  tagged with Parameters