使用数据提供程序编写Java测试

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

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

JUnit 4具有参数化测试,它与php数据提供者的function相同

@RunWith(Parameterized.class) public class MyTest{ @Parameters public static Collection 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 } } 

我们公司的同事为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的手册页上找到。 它还有一些function,比如在实用程序类中收集提供程序以及从其他类中访问它们等。手册页非常详细,我相信你会发现任何问题都可以解答。

根据您在灵活性与可读性方面的需求,您可以选择Parameterized – junit的内置选项,由dkatzel描述。 其他选项是外部图书馆提供的外部junit跑步者,如zohhak ,你可以这样做:

  @TestWith({ "clerk, 45'000 USD, GOLD", "supervisor, 60'000 GBP, PLATINUM" }) public void canAcceptDebit(Employee employee, Money money, ClientType clientType) { assertTrue( employee.canAcceptDebit(money, clientType) ); } 

或junitParams具有不同的function。 只挑选最适合你的东西

这是另一种选择。 您不必使用Google Guava,这只是我的实现。

它使用与@Parameters的答案相同的@Parameters ,但是不使用带参数的类,@Parameters注释依赖于特定的测试方法,因此您可以选择使用该组参数的方法。

 import java.util.Collection; import com.google.common.collect.ImmutableList; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JUnitParamsRunner.class) public class FrobTester { @SuppressWarnings("unused") private Collection validfrobAndGorpValues() { return ImmutableList.of( new Object[] {"frob28953", 28953}, new Object[] {"oldfrob-189-255", 1890255} ); } @Test @Parameters(method = "validfrobAndGorpValues") public void whenGivenFrobString_thenGorpIsCorrect( String frobString, int expectedGorpValue ) { Frob frob = new Frob(frobString); Assert.assertEquals(expectedGorpValue, frob.getGorpValue()); } }