Omar Montemayor
Omar Montemayor

Reputation: 29

Pass values between TestNG tests

Background: I'm executing tests with TestNG and I have a class annotated with @Test that generates a number, or ID if you will, and that same number is the input value of my second test. Is it possible to pass values between TestNG tests?

Upvotes: 2

Views: 2024

Answers (3)

Alex
Alex

Reputation: 7936

Sure. For example if you have two tests that is related you can pass the values from one test to another via test context attributes:

@Test
public void test1(ITestContext context) { //Will be injected by testNG
    /* Do the test here */
    context.setAttribute("myOwnAttribute", "someTestResult");
}

@Test(dependsOnMethods = "test1")
public void test2(ITestContext context) { //Will be injected by testNG
    String prevResult = (String) context.getAttribute("myOwnAttribute");
}

Upvotes: 1

JockX
JockX

Reputation: 2136

Bad practice or not, it can be accomplished by simply using class fields. Just make sure your cases are executed in predictable order (eg. using @Test(priority) or dependsOn TestNG feature).

Upvotes: 1

xianoss
xianoss

Reputation: 169

You should create one test that handles whole case. Tests can't depend on each other, it's considered as bad practise. If you are using maven order of tests execution can be different in different environments.

Upvotes: 0

Related Questions