lostintranslation
lostintranslation

Reputation: 533

Parameterize @BeforeMethod method in TestNG

I have a base test class for my tests which does the initialisation work before each test.

Here is the code

public class BaseTestParameters {

  MyObj myObj;

  @DataProvider(name = "apiType")   
  public static Object[][] createData() {

     return new Object[][] {{"type", "1"},{"type","2"}};   
  } 

  @BeforeMethod()   
  @Factory(dataProvider = "apiType")   
  public void setup(String type,String param) throws Exception {

     myObj = createMyObject(param);

  }
}

All my test classes extend this base class and they use the myObj for the tests.

myObj has two different ways of creation (depending on param). All the tests will run twice . One with each way of constituting myObj.

How do I enable this scenario ? Using @Factory annotation means I need to return Object[] from that method, but I don't have to return any test classes from that method.

Upvotes: 5

Views: 5409

Answers (1)

talex
talex

Reputation: 20436

You can use @Parameters annotation, but you have to specify values in testng,xml it means you have to have separate testng.xml for each set of parameters.

Here is example:

AppTest.java

public class AppTest {
    @Parameters({"par1", "par2"})
    @BeforeMethod()
    public void setUp(String a, String b) {
        System.out.println("a = [" + a + "], b = [" + b + "]");
    }

    @Test
    public void testApp() {
    }
}

testng.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite1" verbose="1" >

    <test name="Run1" >
        <parameter name="par1"  value="val"/>
        <parameter name="par2"  value="anotherval"/>
        <packages>
            <package name="dummy.java" />
        </packages>
    </test>

    <test name="Run2" >
        <parameter name="par1"  value="newValue"/>
        <parameter name="par2"  value="yetAnotherVal"/>
        <packages>
            <package name="dummy.java" />
        </packages>
    </test>
</suite>

Upvotes: 5

Related Questions