Search code examples
automationparallel-processingtestngfactorydataprovider

How can we use Data Provider in testNG at class level, so it can iteration at class level not on method level?


My class is having 20 tests cases. I want to execute this class with 100 data sets.

for example Iteraton1 for MyClass1 method1 - dataset = user1, password1 method2 - dataset = user1, password1 . . method20 - dataset = user1, password1

Iteraton2 for MyClass method1 - dataset = user2, password2 method2 - dataset = user2, password2 . . method20 - dataset = user2, password2

I tried with @Factory and DataProvider, however it iterates over methods.

import org.testng.annotations.Factory;

public class FactoryClass {
    
    @Factory(dataProvider="dp")
    public Object[] invodeMyTest(String name) {
        Object[] data = new Object[1];
        data[0]= new MyClass1(name);
        //data[1]= new MyClass1("qwer");
        return data;
    }
    
    @DataProvider(name = "dp")
    public static Object[][] dataProvider() throws Exception {
    String[][] names = { {"user1"} , {"user2"} };
    return names;
    }

}

@Test()
public class MyClass1 {
    private String user;

    MyClass1(String user) {
        this.user = user;
    }

    public void f1() {
        System.out.println("Inside f1 - User: " + user + (int) Thread.currentThread().getId());
        System.out.println((int) Thread.currentThread().getId());
    }

    public void f2() {
        System.out.println("Inside f2 - User: " + user + (int) Thread.currentThread().getId());
        System.out.println((int) Thread.currentThread().getId());
    }

    @Test
    public void f3() {
        System.out.println("Inside f2 - User: " + user + (int) Thread.currentThread().getId());
        System.out.println((int) Thread.currentThread().getId());
    }

}

Current execution: f1 f1 f2 f2 f3 f3

Required execution: f1 f2 f3 f1 f2 f3

Can someone help how can we achive iteration at class level instead of method level?


Solution

  • Please do the following:

    1. Create a suite xml file for your test class.
    2. Set the attribute group-by-instances="true" at either the <test> level or at the <suite> level.