简体   繁体   English

如何编写带有参数的单元测试?

[英]How to write unit tests with parameters?

I am not familiar to java but in c#(NUnit) you can parameterize unit tests by adding [TestCase] attribute as following: 我对Java不熟悉,但是在c#(NUnit)中,您可以通过添加[TestCase]属性来参数化单元测试,如下所示:

[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
   Assert.AreEqual( q, n / d );
}

In this case we do not have to write seperate unit test for every test case. 在这种情况下,我们不必为每个测试用例编写单独的单元测试。 Instead we have writing [TestCase] to change the value. 相反,我们编写了[TestCase]来更改值。

Are there any equivelant on Java? 在Java上有什么不对等的地方吗? Currently using Junit 4.12 当前使用Junit 4.12

Parameterized is what you need. 参数化是您所需要的。 Consider the below example. 考虑下面的示例。 Note that test3 is obviously RED as 20/5 = 4. 请注意,test3显然是红色的,为20/5 = 4。

import static org.junit.Assert.assertEquals;

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

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

@RunWith(Parameterized.class)
public class DividerTest {

  private int dividend;
  private int divisor;
  private int expectedResult;

  @Parameterized.Parameters
  public static Collection<Object[]> data() {
    Object[] test1 = { 10, 5, 2 };
    Object[] test2 = { 15, 5, 3 };
    Object[] test3 = { 20, 5, 5 };

    return Arrays.asList(test1, test2, test3);
  }

  public DividerTest(int dividend, int divisor, int expectedResult) {
    this.dividend = dividend;
    this.divisor = divisor;
    this.expectedResult = expectedResult;
  }

  @Test
  public void testDivider() {
    assertEquals(expectedResult, dividend / divisor);
  }
}

And here are the test results: 这是测试结果:

在此处输入图片说明

TestNG是一个库和框架,可以使用数据工厂和依赖项注入对测试参数进行出色的控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM