Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestNG - sharing state between test classes

Tags:

java

testng

I have a testng suite of test classes that I am running via a testng.xml file. This works fine. All tests are run serially, so no parallel-execution hurdles.

My goal now is to take state that was generated by the test methods in one test class (e.g., a customerId primary key value generated by a database insert) and pass it along to another test class, so that the test methods in that second class can take further action based on that shared state (e.g., look up the just-inserted customer using the customerId value from the first class).

It's easy to share state between test methods in a single class, of course, via class member variables, but I don't see how to share it across test classes.

like image 722
ricb Avatar asked Jul 15 '14 19:07

ricb


2 Answers

Really Testng-y way to do this is to set ITestContext attribute with desired value and then get it from other test class.

Set value:

@Test
public void setvaluetest(ITestContext context) {
        String customerId = "GDFg34fDF";
        context.setAttribute("customerId", customerId);
}

Get value:

@Test
public void getvaluetest(ITestContext context) {
        String id = context.getAttribute("customerId");
}
like image 86
Dmitry Glushonkov Avatar answered Oct 05 '22 14:10

Dmitry Glushonkov


Use a factory to create a repository. The repository stores "interesting test state" properties.

  TestRepository tr = TestRepositoryFactory.getInstance();
  ...
  tr.store("test13.PKID", pkid.toString());

and then in your subsequent code, repeat the call to the factory and then get the value:

  String spkid = tr.get("test13.PKID");
like image 23
Bob Dalgleish Avatar answered Oct 05 '22 14:10

Bob Dalgleish