How To Run one @dataprovider against multiple @test methods

85 views
Skip to first unread message

sayanta Bera

unread,
Jun 7, 2023, 6:11:39 AM6/7/23
to testng-users
Have tried with @Factory

@Factory(dataProvider="UserUIOperations")

public UsersUIOperationsTest(HashMap<String, String> input) {

this.data=input;

}

@DataProvider(name = "UserUIOperations")

public Object[][] createData() {

try {

Object[][] retObjArr = DataGenerator.getDataTable(testDataFileName, workSheetName);

return retObjArr;

} catch (Throwable e) {

FrameworkBase.logger.info(e);

return new Object[][] { {} };

}

}


@Test(dependsOnMethods ="UserCreationWithMandatoryFields" )

public void case2(HashMap<String, String> input) throws Exception {



FrameworkBase.logger

.info("================START OF TEST CASE : " + input.get("TestDescription") + "==================");

String[] test_steps = input.get("TestSteps").split(",");

for (String test_step : test_steps) {

FrameworkBase.logger.info("################Executing test step:" + test_step + " ##################");

switch (test_step) {

case "Login":

test_step_status = loginInstance.signIn(input.get(FrameworkConstants.LOGINUSER),

input.get(FrameworkConstants.LOGINPASSWORD), input.get("TestDescription"));

break;

case "CreateUser":

test_step_status = createUserIntsance.createUser(input.get("FirstName"), input.get("LastName"),

input.get("CN"), input.get("Password"), input.get("ConfirmPassword"), input.get("Title"),

input.get("Email"), input.get("Telephone_Number"),

input.get("Manager"), input.get("DirectReports"), input.get("UserImage"),

input.get("TestDescription"));

break;

case "DeleteUser":

test_step_status = manageUserInstance.deleteUser(input.get("DeleteSearchField"),

input.get("TestDescription"));

break;


@Test

public void test2(HashMap<String, String> input){

}

Getting this error:-

[AppClassLoader@12bb4df8] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified

org.testng.TestNGException:

Cannot instantiate class com.microfocus.idmappsui.tests.UsersUIOperationsTest

at org.testng.internal.InstanceCreator.newInstance(InstanceCreator.java:36)

at org.testng.internal.objects.SimpleObjectDispenser.dispense(SimpleObjectDispenser.java:40)

at org.testng.internal.objects.GuiceBasedObjectDispenser.dispense(GuiceBasedObjectDispenser.java:30)

at org.testng.internal.Parameters.findDataProvider(Parameters.java:651)

at org.testng.internal.Parameters.findDataProvider(Parameters.java:553)

at org.testng.internal.Parameters.handleParameters(Parameters.java:772)

at org.testng.internal.FactoryMethod.invoke(FactoryMethod.java:149)

at org.testng.internal.TestNGClassFinder.processFactory(TestNGClassFinder.java:182)

at org.testng.internal.TestNGClassFinder.processMethod(TestNGClassFinder.java:142)

at org.testng.internal.TestNGClassFinder.processClass(TestNGClassFinder.java:133)

at org.testng.internal.TestNGClassFinder.<init>(TestNGClassFinder.java:71)

at org.testng.TestRunner.initMethods(TestRunner.java:443)

at org.testng.TestRunner.init(TestRunner.java:339)

at org.testng.TestRunner.init(TestRunner.java:292)

at org.testng.TestRunner.<init>(TestRunner.java:223)

at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)

at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)

at org.testng.ITestRunnerFactory.newTestRunner(ITestRunnerFactory.java:55)

at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:659)

at org.testng.SuiteRunner.init(SuiteRunner.java:173)

at org.testng.SuiteRunner.<init>(SuiteRunner.java:107)

at org.testng.TestNG.createSuiteRunner(TestNG.java:1300)

at org.testng.TestNG.createSuiteRunners(TestNG.java:1276)

at org.testng.TestNG.runSuitesLocally(TestNG.java:1125)

at org.testng.TestNG.runSuites(TestNG.java:1063)

at org.testng.TestNG.run(TestNG.java:1031)

at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)

at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)

at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Caused by: java.lang.InstantiationException: com.microfocus.idmappsui.tests.UsersUIOperationsTest

at java.base/java.lang.Class.newInstance(Class.java:571)

at org.testng.internal.InstanceCreator.newInstance(InstanceCreator.java:30)

... 28 more

Caused by: java.lang.NoSuchMethodException: com.microfocus.idmappsui.tests.UsersUIOperationsTest.<init>()

at java.base/java.lang.Class.getConstructor0(Class.java:3349)

at java.base/java.lang.Class.newInstance(Class.java:556)

... 29 more

⇜Krishnan Mahadevan⇝

unread,
Jun 7, 2023, 6:16:54 AM6/7/23
to testng...@googlegroups.com
Please include the following:

1. What version of TestNG are you using? Latest released versions are [7.5.1 if you are on JDK8 and 7.8.0 if you are on JDK11]
2. Can you share a simple standalone example that can be used to reproduce the problem (Preferably a maven sample project)
3. How are you running your test to trigger this problem [ Is it via IntelliJ (or) eclipse (or) via a build tool such as Gradle/Maven ]
4. If the problem is via an IDE, then you would need to share the plugin details as well.
5. Does this work at all for you or is this a problem that comes up in all modes of execution?


Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/


--
You received this message because you are subscribed to the Google Groups "testng-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to testng-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/testng-users/c635ed39-a7f6-4cf5-9986-6858f7025523n%40googlegroups.com.

sayanta Bera

unread,
Jun 8, 2023, 2:32:20 AM6/8/23
to testng-users
Hi,

I have resolved the above issue, and answered to your above queries.
kindly assist me on the same.



1. What version of TestNG are you using? Latest released versions are [7.5.1 if you are on JDK8 and 7.8.0 if you are on JDK11]
Ans: testng version 7.0.0 and JDK 8

2. Can you share a simple standalone example that can be used to reproduce the problem (Preferably a maven sample project)

Need few clarification on below questions:-

1) can we map or run one row from excel against one test method.

suppose i have 10 test cases in excel (test-sheet) , want to execute each test case once against each test method. 

test1(row1 data: login page)     will run against @test method1
test2(row2 data: logout page)  will run against @test method2
test3(row3 data: Home page)  will run against @test method3 

similarly remaining test cases will run against it's remaiminig  @test method.

Want to achieve above mechanism.

3. How are you running your test to trigger this problem [ Is it via IntelliJ (or) eclipse (or) via a build tool such as Gradle/Maven ]
Ans: Eclipse maven

4. If the problem is via an IDE, then you would need to share the plugin details as well.
Ans: IDE is working fine.

5. Does this work at all for you or is this a problem that comes up in all modes of execution?
Ans: trying to do new implementation on framework level.


Hope the requirement is clear to you, Let me know if you need any further information.

Regards,
sayanta.

⇜Krishnan Mahadevan⇝

unread,
Jun 8, 2023, 3:29:47 AM6/8/23
to testng...@googlegroups.com
The below sample is perhaps what you are looking for (Feel free to enhance it to work with excel spreadsheets as well)
For your understanding, I have added inline comments which explains what is going on.

Note: Please use 7.5.1 (If on JDK8) and 7.8.0 (if on JDK11).

Java
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.Map;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DynamicTestCase {

  private static Map<String, Map<String, String>> allData;

  @Test(description = "bangalore", dataProvider = "dp")
  public void bangaloreRecordsTest(Map<String, String> testData) {
    Map<String, String> expected = Map.of("language", "kannada", "status", "non-metro",
        "is_analysed", "false");
    System.err.println("bangaloreRecordsTest() test data was ==> " + testData);
    assertThat(testData).containsAllEntriesOf(expected);
  }

  @Test(description = "chennai", dataProvider = "dp")
  public void chennaiRecordsTest(Map<String, String> testData) {
    Map<String, String> expected = Map.of("transport_corp_name", "SETC", "language", "tamil");
    System.err.println("chennaiRecordsTest() test data was ==> " + testData);
    assertThat(testData).containsAllEntriesOf(expected);
  }

  @Test(dataProvider = "dp")
  public void kolkattaRecordsTest(Map<String, String> testData) {
    //This test will be run twice because there are two sets of test data
    System.err.println("kolkattaRecordsTest() test data was ==> " + testData);
  }

  @DataProvider(name = "dp")
  public Object[][] getTestData(Method method) {
    if (allData == null) {
      //This is to ensure that we try and read data from our data source (For e.g., excel sheet)
      //only once even though our data provider may be called "n" times by different test methods
      allData = readAllTestData();
    }

    Test test = method.getAnnotation(Test.class);
    //We use the description as a mechanism to tell us which row a test wants to execute
    //This can always be done by adding a custom annotation as well and then parsed based on that.
    String filterKey = test.description();
    if (filterKey == null || filterKey.trim().isEmpty() || !allData.containsKey(filterKey)) {
      //We will return back all the test data for all the cities if we find that
      //there was no key specified (or) if the key specified is not present in our data source
      return allData.values()
          .stream()
          .map(each -> new Object[]{each})
          .toArray(Object[][]::new);
    }
    return new Object[][]{
        new Object[]{allData.get(filterKey)}
    };

  }

  private static Map<String, Map<String, String>> readAllTestData() {
    return Map.of(
        "chennai", Map.of("transport_corp_name", "SETC", "language", "tamil"),
        "bangalore", Map.of("language", "kannada", "status", "non-metro", "is_analysed", "false")
    );
  }
}



Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/

sayanta Bera

unread,
Jun 9, 2023, 3:50:01 AM6/9/23
to testng-users
Hi Krishnan,

I have implimented dataprovider as below
 @DataProvider(name = "UserUIOperations")
public Object[][] createData(Method m) {
    Object[][] retObjArr = null;
try {
retObjArr = DataGenerator.getDataTable(testDataFileName, workSheetName); //return whole excel data
ArrayList<String>  getdata=DataGenerator.getDesc(testDataFileName, workSheetName); //return all test-descriptions

Test test= m.getAnnotation(Test.class);
System.out.println("the length of retObjArr="+retObjArr.length);

for(int i=0;i<retObjArr.length;i++) {
int j=0;
System.out.println(retObjArr[i][j]);

if(test.description().equals(getdata.get(0))) { //for now have hardcoded {get(0)}the value just for validating once.
return (Object[][]) retObjArr[i][j]; //returning new data set everytime based on condition.
}
}
}
     catch (Throwable e) {
     }
return null;
     }
My data provider should always return an updated value each time, which I am unable to do. Could you please suggest how can I enhance my return type, that will help.
This is my Excel data sheet. Here each row represents one test case.
Regards,
Sayanta
TestData.png

⇜Krishnan Mahadevan⇝

unread,
Jun 9, 2023, 5:09:37 AM6/9/23
to testng...@googlegroups.com
I am not sure I quite understand what you need additionally apart from what I already shared with you as a sample.
  • You can add a new column to your excel spreadsheet called "testCaseId".
  • Set the "testCaseId" via the "@Test" annotation's description attribute.
  • Read the "testCaseId" from the "description" attribute of the "@Test" annotation in your "@DataProvider" method, filter the rows based on the value from the "testCaseId" and then return back the value.
Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/

sayanta Bera

unread,
Jun 9, 2023, 5:43:51 AM6/9/23
to testng-users
Thank you :) for all the inputs.
Finally able to achieve what I wanted to do.

Regards,
Sayanta

Reply all
Reply to author
Forward
0 new messages