Passing output of one test method to another metho

2019-01-15 14:42发布

问题:

I have to write the following unit test cases in testng:

  1. saveProductTest which would return productId if product details are saved successfully in DB.

  2. modifyProductTest, it should use previously saved productId as a parameter.

I am taking the product details input(PrdouctName, ReleaseDate) for saveProductTest and modifyProductTest method from an XML file using testNg data providers.Since productId is generated in save method, I have to pass it to the modify method.

What is the best way to pass output of one test method to another method in testng.

回答1:

With all due respect to simendsjo, the fact that all tests should be independent from each other is a dogmatic approach that has a lot of exceptions.

Back to the original question: 1) use dependent methods and 2) store the intermediate result in a field (TestNG doesn't recreate your instances from scratch, so that field will retain its value).

For example

private int mResult;

@Test
public void f1() {
  mResult = ...
}

@Test(dependsOnMethods = "f1")
public void f2() {
  // use mResult
}


回答2:

With the ITestContext object. It's a object available globally at the Suite context and disponible via parameter in each @Test.

For example:

@Test 
public void test1(ITestContext context, Method method) throws Exception {
    // ...
    context.setAttribute(Constantes.LISTA_PEDIDOS, listPaisPedidos);
    // ...
}

@Test
public void test2(ITestContext context, Method method) throws Exception {
    List<PaisPedido> listPaisPedido = (List<PaisPedido>)
    context.getAttribute(Constantes.LISTA_PEDIDOS);
    // ...
}


回答3:

Each unit test should be independent of other tests so you more easily can see what fails. You can have a helper method saving the product and returning the id and call this from both tests.



标签: java testng