The Kaptain on … stuff

09 Aug, 2009

Using the TestNG DataProvider with Groovy

Posted by: TheKaptain In: Development

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.

🙂

3 Responses to "Using the TestNG DataProvider with Groovy"

1 | Dah

August 10th, 2009 at 6:24 am

Avatar

You are missing a “classifier” in your pom.xml when declaring the dependency on testng. Without that, i had no luck running your example.

2 | TheKaptain

August 10th, 2009 at 6:50 am

Avatar

Thanks for noting that!
The classifier referred to is this blurb in the testng maven dependency declaration:

jdk15

And I will add that to the repo asap. Thanks for the assist.

3 | TheKaptain

August 10th, 2009 at 4:04 pm

Avatar

Github pom.xml has been updated with the missing testng classifier element.

Comment Form