使用数据提供程序编写 Java 测试 [英] Writing Java tests with data providers

查看:16
本文介绍了使用数据提供程序编写 Java 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在做我的第一个 Java 项目并且喜欢完全 TDD 它.我正在使用 JUnit 来编写测试.显然 JUnit 不支持 data提供者,这使得用 20 个不同版本的参数测试相同的方法变得相当烦人.支持数据提供程序的最流行/标准的 Java 测试工具是什么?我遇到了 TestNG,但不知道它有多受欢迎,或者它与替代品相比如何.

I'm currently doing my first Java project and like to fully TDD it. I'm using JUnit for writing the tests. Apparently JUnit does not provide support for data providers, which makes it rather annoying to test the same method with 20 different versions of an argument. What is the most popular/standard testing tool for Java that does support data providers? I came across TestNG, but have no idea how popular that one is, or how it compares to alternatives.

如果有一种方法是使用 JUnit 来获得这种行为的好方法,那么这也可能有效.

If there is a way to get this behaviour is a nice way using JUnit, then that might also work.

推荐答案

JUnit 4 有参数化测试,它与 php 数据提供者做同样的事情

JUnit 4 has parameterized test which is the does the same thing as php data providers

@RunWith(Parameterized.class)
public class MyTest{ 
     @Parameters
    public static Collection<Object[]> data() {
           /*create and return a Collection
             of Objects arrays here. 
             Each element in each array is 
             a parameter to your constructor.
            */

    }

    private int a,b,c;


    public MyTest(int a, int b, int c) {
            this.a= a;
            this.b = b;
            this.c = c;
    }

    @Test
    public void test() {
          //do your test with a,b
    }

    @Test
    public void testC(){
        //you can have multiple tests 
        //which all will run

        //...test c
    }
}

这篇关于使用数据提供程序编写 Java 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆