使用数据提供者编写 Java 测试

新手上路,请多包涵

我目前正在做我的第一个 Java 项目,并希望对其进行全面的测试驱动开发。我正在使用 JUnit 编写测试。显然 JUnit 不提供对 数据提供者 的支持,这使得用 20 个不同版本的参数测试同一个方法变得相当烦人。支持数据提供程序的最流行/标准的 Java 测试工具是什么?我遇到了 TestNG ,但不知道它有多受欢迎,也不知道它与替代方案相比如何。

如果有一种方法可以使这种行为成为一种使用 JUnit 的好方法,那么它也可能会起作用。

原文由 Jeroen De Dauw 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 333
2 个回答

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

@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
    }
}

原文由 dkatzel 发布,翻译遵循 CC BY-SA 3.0 许可协议

我在我们公司的同事为 JUnit 编写了一个免费的 TestNG 风格的 DataProvider,您可以 在 github (https://github.com/TNG/junit-dataprovider) 上 找到它。

我们在非常大的项目中使用它,它对我们来说工作得很好。它比 JUnit 的 Parameterized 有一些优势,因为它将减少单独类的开销,并且您也可以执行单个测试。

一个例子看起来像这样

@DataProvider
public static Object[][] provideStringAndExpectedLength() {
    return new Object[][] {
        { "Hello World", 11 },
        { "Foo", 3 }
    };
}

@Test
@UseDataProvider( "provideStringAndExpectedLength" )
public void testCalculateLength( String input, int expectedLength ) {
    assertThat( calculateLength( input ) ).isEqualTo( expectedLength );
}

编辑: 从 v1.7 开始,它还支持其他方式提供数据(字符串、列表),并且可以内联提供程序,因此不一定需要单独的方法。

可以在 github 上的手册页上找到完整的工作示例。它还具有更多功能,例如在实用程序类中收集提供程序并从其他类访问它们等。手册页非常详细,我相信您会在那里找到任何问题的答案。

原文由 Ingo Bürk 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题