TestNG – @Factory Annotation
@Factory
allows tests to be created at run time depending on certain data-sets or
conditions.
Sometimes we
may need to run a set of tests with different data values. To achieve this we
may define a separate set of tests inside a suite in the testng XML and test
the required scenario. The problem with this approach is that, if you get an
extra set of data, you will need to redefine the test. TestNG solves this
problem by providing the @Factory annotation feature. Factory in TestNG defines
and creates tests dynamically at run time.
Basic Factory Example
Let’s create
a sample program using the @Factory annotation of TestNG.
public class
SimpleTest
@Test
public void simpleTest() {
System.out.println("Simple Test
Method.");
}
}
public class
SimpleTestFactory
{
@Factory
public Object[] factoryMethod() {
return new Object[] { new SimpleTest(),
new SimpleTest() };
}
}
The
preceding class defines a factory method inside it. A factory method is defined
by declaring @Factory above the respective test method. It’s mandatory that a
factory method should return an array of Object class (Object []).
Let’s run
the factory now.
Simple Test
Method.
Simple Test
Method.
PASSED:
simpleTest
PASSED:
simpleTest
As you can
see in the preceding test results, the test method from the SimpleTestFactory
class was executed two times. The execution is based on the Object array
returned by the factory method. As the said method returns two objects of the
SimpleTest class, TestNG looks inside the specified returned object and
executes all the test methods inside it. In this case, as there was only one
test method, TestNG executes the respective test method.
No comments:
Post a Comment