Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test NG - pass parameter with setTestClasses()

I'm using the programmatically approach to run tests included in the Courier class.

TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { Courier.class });
testng.addListener(tla);
testng.run();

How is it possible to pass parameter to tests included in this class? e.g.

testng.setTestClasses(new Class[] { Courier("parameter").class });

Courier:

public class Courier {
@Parameter(passed parameter)
@Test
public void Courier_Test(String parameter){
    System.out.println(parameter);
}   

}

Thanky for any help !

like image 868
Thomas Avatar asked Nov 29 '25 15:11

Thomas


1 Answers

A couple of ideas:

Even if you are running the tests programmatically, you should be able to invoke TestNG on a testng.xml file. Add parameters to the file like so (from the documentation):

<suite name="My suite">
   <parameter name="parameter"  value="Foo"/>
   <test name="Courier Test" />
   < ... >

If for some reason you aren't using a testng.xml file, you can use a DataProvider, either as a method within the test class or as a static class, depending on what you need to do. Examples below (also from the documentation).

DataProvider inside the class:

//This method will provide data to any test method that declares
//that its Data Provider is named "test1"
@DataProvider(name = "test1")
public Object[][] createData1() {
   return new Object[][] {
     new Object[] { "Parameter" }
   }
}

//This test method declares that its data should be supplied 
//by the Data Providernamed "test1"
@Test(dataProvider = "test1")
public void Courier_Test(String parameter) {
 System.out.println(parameter);
} 

DataProvider in external class:

public static class StaticProvider {
  @DataProvider(name = "create")
  public static Object[][] createData() {
    return new Object[][] {
      new Object[] { "Parameter" }
    }
  }
}

public class Courier {
  @Test(dataProvider = "create", dataProviderClass = StaticProvider.class)
  public void Courier_Test(String parameter) {
    // ...
  }
}
like image 169
Feanor Avatar answered Dec 01 '25 05:12

Feanor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!