TestNG is a great tool for testing in Java, and it works even better with a little Groovy thrown in. Just lately I’ve had a lot of success using the DataProvider pattern.
A DataProvider method in TestNG can return either a two dimensional Object array or an Iterator over each of the test parameters. A consumer of that method will be triggered once time for each set of parameters from the provider. Parameters are injected into the consumer method at execution time.
This greatly eases testing various expectations that run through essentially the same path of execution.
Here’s the simple method under test, courtesy of this example on Groovy Almanac
[groovy language=”true”]
/**
* Use the Groovy added List.inject() method to sum a list of numbers.
*/
def sum(list)
{
def sum = list.inject(0) { sum, item -> sum + item }
}
[/groovy]
And here’s the corresponding DataProvider test harness. The test is injected with a List of numbers to sum and the associated total expected for each case.
[groovy language=”true”]
@DataProvider (name = "test1")
public Object[][] createListInjectSumData() {
def array = new Object[3][]
array[0] = [[1, 2, 3], 6] as Object[]
array[1] = [[2, 4, 6], 12] as Object[]
array[2] = [[3, 6, 9], 18] as Object[]
return array
}
@Test (dataProvider = "test1")
void testListInjectSummation(list, expectedSum) {
Assert.assertEquals(new ListInjectExample().sum(list), expectedSum)
}
[/groovy]
I’ve put the maven project I used to demo this up on github here. Mostly just because I’m having a great time using Git lately.
🙂