TestNG Factory Annotation
What is @Factory Annotation?
TestNG Factory annotation feature allows us to create tests dynamically at run-time. Factory will execute all the @Test methods in the test class using a separate instance of the test class.
We will go through a code example to explain about @Factory annotated method.
Code Listing
package com.testingdocs.testng.sample;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class FactoryExampleClass
{
String testdata ;
int objectID ;
public FactoryExampleClass(int ojectID, String testdata)
{
this.objectID = ojectID ;
this.testdata= testdata ;
}
@BeforeClass
public void beforeClass(){
System.out.println("This is before class of " + objectID);
}
@Test
public void testmethod(){
System.out.println("This is test method, testdata is :" + testdata);
}
@AfterClass
public void afterClass(){
System.out.println("This is after class of " + objectID);
}
}
Now we would write the @Factory method which runs 3 times as shown below.
package com.testingdocs.testng.sample;
import org.testng.annotations.Factory;
public class TestNGFactory
{
@Factory
public static Object[] testData()
{
Object[] object = new Object[3];
object[0]= new FactoryExampleClass(1,"testdata1");
object[1]= new FactoryExampleClass(2,"testdata2");
object[2]= new FactoryExampleClass(3,"testdata3");
return object;
}
}
Run result
This is before class of 1
This is test method, testdata is :testdata1
This is after class of 1
This is before class of 3
This is test method, testdata is :testdata3
This is after class of 3
This is before class of 2
This is test method, testdata is :testdata2
This is after class of 2
PASSED: testmethod
PASSED: testmethod
PASSED: testmethod
===============================================
Default test
Tests run: 3, Failures: 0, Skips: 0
===============================================
Look how we have executed the test method multiple times run-time for different testdata . ( 3 times in the above example )
Common Problem
Common problems are exceptions in Factory methods. Any exception in the factory method would throw an exception like as shown below sample exception trace.:
org.testng.TestNGException:
The factory method class com.testingdocs.testng.sample.TestNGFactory.testData() threw an exception
We need to debug the root cause of the exception in the factory method.TestNG internal code that displays the error is as shown below:
catch (Throwable t) {
ConstructorOrMethod com = getConstructorOrMethod();
throw new TestNGException("The factory method "
+ com.getDeclaringClass() + "." + com.getName()
+ "() threw an exception", t);
}