TestNG factory class with example

TestNG factory class is used to create instance of testNg class at runtime (dynamically). When we apply Factory annotation on method, it always return object array of Object class ( “Object[]”). This is useful annotation when you run test multiple time.

TestNG pick @Factory method from class and consider each object mentioned in factory test as a TestNg class and invoke in separate.

Example:  FactoryClassImp.java
package com.tests;

import org.testng.annotations.Factory;

public class FactoryClassImp {

 @Factory
 public Object[] createTest() {
  Object[] res = new Object[3];
  res[0] = new FactoryTestClass(2, 2);
  res[1] = new FactoryTestClass(2, 3);
  res[2] = new FactoryTestClass(2, 4);

  return res;
 }
}



TestNg class file (TestNgTestClass.java)
package com.tests;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestNgTestClass {
 int a;
 int b;

 public TestNgTestClass(int a, int b) {
  this.a = a;
  this.b = b;
 }

 @Test
 public final void testEqual() { 
  Assert.assertEquals(a , b);
 }
}

Run FactoryClassImp.java file using TestNG, you will see that three instance will execute of class TestNgTestClass.

No comments:

Post a Comment

Leave your comments, queries, suggestion I will try to provide solution