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 - Exception Test

In this post I will show you how to handle exception in Testng. TestNg provides expectedExceptions parameter  which is used along with @Test annotation, exp @Test(expectedExceptions)

package com.test;

import org.testng.annotations.Test;

public class TestNgException {

        @Test(expectedExceptions = ArithmeticException.class)
        public void testException() {
               int a = 10;
               int b = 0;
               a = a / b;
        }

        @Test
        public void testException1() {
               int a = 10;
               int b = 0;
               a = a / b;
        }
}

In test method testException I used “@Test(expectedExceptions = ArithmeticException.class)” so airthmetic exception handle but in  test testException1 exception generated.

TestNG - Ignore Test

In this post I will show you how to ignore testng test case to execute,  TestNg provide attribute enabled which make the test to be execute or not, if test mark @Test(enabled = false) then test will not execute. By default enabled value is true.

Here is example for ignore test case:

package com.test;

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

public class IgnoreTestClass {

        @Test
        public void testMethod1() {
               Assert.assertTrue(true);
        }

        @Test(enabled = false)
        public void testMethod2() {
               Assert.assertTrue(true);
        }

        @Test(enabled = true)
        public void testMethod3() {
               Assert.assertTrue(true);
        }
}

Run above test you will see that testMethod2 will ignored and not executed:

PASSED: testMethod1
PASSED: testMethod3

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 2, Failures: 0, Skips: 0
====================================