TestNG @Factory annotation is used to specify a method as a factory for providing objects to be used by TestNG for test classes. The method marked with @Factory annotation should return Object array.

TestNG @Factory Annotation

TestNG Factory is useful when you want to run multiple test classes through a single test class. Let’s see a quick example of TestNG Factory annotation.

Let’s say we have two Test classes with few test methods defined.

Now we can define a Factory method that returns the Object array of above classes.

Below image shows the output of running above class as TestNG test class.

Here is the output produced in the Eclipse Console.

Note that if we do the maven build and there are more TestNG test classes present, all of them will also get executed. I have another TestNG test class and below is the output from maven build.

So if the Test class is getting returned by any factory method, then it’s excluded from the default test suite.

We can also create multiple @Factory methods in the same test class or in different test classes.

TestNG Factory with DataProvider

When we do project build, all our test cases are being executed. So what’s the benefit of using Factory method?

Well, it’s beneficial when you use it with DataProvider and your test class constructor has arguments.

Let’s say our Test1 class is defined as:

If we simply run this class as TestNG test class, then it will assign the default value for the string argument of the constructor and produce following output.

In this case, we can use DataProvider along with Factory to provide inputs for the constructor.

When we run above test class, it produces following output.

Summary

TestNG Factory methods are useful when your test classes have constructors with arguments or you want to create the different set of test classes and execute them at once.

By admin

Leave a Reply

%d bloggers like this: