Dynamic Test-NG Tests

In my last few projects, I have used Test-NG.  Uniquely in my current project, I had to generate tests programmatically.  Instead of writing one test for each element in the project, I am able to generate a bunch at-will using the following pattern:

Factory

package test;

import org.testng.annotations.Factory;

public class DynamicTestFactory {


    @Factory
    public Object[] createInstances() {
        
     Object[] result = new Object[10]; 
     for (int i = 0; i < 10; i++) {
        result[i] = new ExampleProcessorTest(Integer.toString(i * 10)+ "A",Integer.toString(i*10) + "B");
      }
      return result;
    }
    
}

Test


package test;

import static org.testng.Assert.assertTrue;

import org.testng.annotations.Test;
 
public class ExampleProcessorTest {

    private String a; 
    private String b; 
    
    public ExampleProcessorTest(String a, String b) {
        this.a = a;
        this.b = b;
        
    }
    
    @Test
    public void testServer() {
        System.out.println("TEST");
        assertTrue(true);;
    }
}

Running Code

[RemoteTestNG] detected TestNG version 6.9.10
[TestNG] Running:
/private/var/folders/07/sw3n5r3170q202d5j4tx8fhw0000gn/T/testng-eclipse--1754065412/testng-customsuite.xml

TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
TEST
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer

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


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

[TestNG] Time taken by org.testng.reporters.EmailableReporter2@76a4d6c: 9 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 5 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@32cf48b7: 4 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@130f889: 23 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@6e2c9341: 8 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@58a90037: 10 ms
I can also trigger using testng.xml
<class name="DynamicTestFactory" />

Reference

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.