junit4做参数化测试

来源:互联网 发布:linux操作系统源码 编辑:程序博客网 时间:2024/05/17 02:38

用JUnit4进行参数化测试

  参数化测试是一个JUnit 3不具备的功能。

 

基本使用方法

  @RunWith

  当类被@RunWith注解修饰,或者类继承了一个被该注解修饰的类,JUnit将会使用这个注解所指明的运行器(runner)来运行测试,而不是JUnit默认的运行器。

  要进行参数化测试,需要在类上面指定如下的运行器:

  @RunWith (Parameterized.class)

  然后,在提供数据的方法上加上一个@Parameters注解,这个方法必须是静态static的,并且返回一个集合Collection

  

  在测试类的构造方法中为各个参数赋值,(构造方法是由JUnit调用的),最后编写测试类,它会根据参数的组数来运行测试多次

 

文档中的例子

  Class Parameterized的文档中有一个例子:

  For example, to test a Fibonacci function, write:

  

复制代码
    @RunWith(Parameterized.class)    public class FibonacciTest    {        @Parameters        public static Collection data()        {            return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },                    { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });        }        private int fInput;        private int fExpected;        public FibonacciTest(int input, int expected)        {            fInput = input;            fExpected = expected;        }        @Test        public void test()        {            assertEquals(fExpected, Fibonacci.compute(fInput));        }    }
复制代码

 

参数化测试实例

  还是以前面的Calculator类作为例子,进行参数化测试:

Calculator
package com.mengdd.junit4;public class Calculator{    public int add(int a, int b)    {        return a + b;    }    public int subtract(int a, int b)    {        return a - b;    }    public int multiply(int a, int b)    {        return a * b;    }    public int divide(int a, int b) throws Exception    {        if (0 == b)        {            throw new Exception("除数不能为0");        }        return a / b;    }}

  参数化测试加法的类:

复制代码
package com.mengdd.junit4;import java.util.Arrays;import java.util.Collection;import org.junit.Assert;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)// 指定运行器runner:使用参数化运行器来运行public class ParametersTest{    private int expected;// 期待的结果值    private int input1;// 参数1    private int input2;// 参数2    private Calculator calculator = null;    @Parameters    public static Collection prepareData()    {        // 测试数据        Object[][] objects = { { 3, 1, 2 }, { -4, -1, -3 }, { 5, 2, 3 },                { 4, -4, 8 } };        return Arrays.asList(objects);// 将数组转换成集合返回    }    @Before    public void setUp()    {        calculator = new Calculator();    }    public ParametersTest(int expected, int input1, int input2)    {        // 构造方法        // JUnit会使用准备的测试数据传给构造函数        this.expected = expected;        this.input1 = input1;        this.input2 = input2;    }    @Test    public void testAdd()    {        Assert.assertEquals(this.expected,                calculator.add(this.input1, this.input2));    }}
0 0
原创粉丝点击