多组数据的单元测试:用JUnit4做参数化测试

发表于:2018-11-06 11:28

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:圣骑士Wind    来源:51testing采编

分享:
  基本使用方法
  @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类作为例子,进行参数化测试:
  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));
  }
  }

  上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。

《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号