Java Unit Testing : JUnit Vs TestNG

Just wanted share thought with you all about two very well accepted unit testing frameworks (JUnit and TestNG) in Java world, off course there are lots of differences in these two but I wanted to share the one I encountered today. I found built-in Parameterized runner is quite crude in Junit4 as compare to TestNG (I know each framework has its strengths but still).In JUnit we are not allowed to write more than one data providing methods with annotation @parameters . I encountered this problem while testing the valid and invalid behavior for functionality in same test class. So the first public, static annotated javascript:void(0)method that it finds will be used, but it may find them in any order. This causes us to write different classes unnecessarily. However TestNG provides clean way to provide different kind of data providers for each and every method. So we can test the same unit of code with valid and invalid way in same test class putting the valid/invalid data separately.
Examples:
JUnit4:

Here we can not specify value for @parameters so it will be only and even if we have multiple methods the runner will return one of them. So we can provide only one kind of data Valid or invalid.
TestNG:

@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(Class clzz, String[] number) {
System.out.println("Parameterized Number is : " + number[0]);
System.out.println("Parameterized Number is : " + number[1]);
}

//This function will provide the patameter data or we can use xml as well
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {
return new Object[][]{
{Vector.class, new String[] {"java.util.AbstractList", "java.util.AbstractCollection"}},
{String.class, new String[] {"1", "2"}},
{Integer.class, new String[] {"1", "2"}}
};
}


Here in this case we can create as many data provider functions as we can and associate with appropriate method using @dataprovider.


About this entry


2 comments:

  1. Geoff August 3, 2009 at 6:09 AM

    Ravindra, can you share an example of using the parameterized tests/data providers? That would probably help us understand better.

    Thanks.

     
  2. Ravindra Nikam August 3, 2009 at 6:18 AM

    yeah sure , here it is

    please check above I have updates post for you.