java 将一种测试方法的输出传递给另一种方法 testng
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3115822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing output of one test method to another method testng
提问by Rakesh Goyal
I have to write the following unit test cases in testng:
我必须在 testng 中编写以下单元测试用例:
saveProductTest which would return productId if product details are saved successfully in DB.
modifyProductTest, it should use previously saved productId as a parameter.
如果产品详细信息成功保存在数据库中,则 saveProductTest 将返回 productId。
modifyProductTest,它应该使用之前保存的 productId 作为参数。
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.
我正在使用 testNg 数据提供程序从 XML 文件中获取 saveProductTest 和 modifyProductTest 方法的产品详细信息输入(PrdouctName、ReleaseDate)。由于 productId 是在 save 方法中生成的,因此我必须将其传递给 modify 方法。
What is the best way to pass output of one test method to another method in testng.
将一种测试方法的输出传递给 testng.xml 中的另一种方法的最佳方法是什么?
回答by Cedric Beust
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.
恕我直言 simendsjo,所有测试都应该相互独立这一事实是一种教条式的方法,有很多例外。
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).
回到最初的问题:1) 使用依赖方法和 2) 将中间结果存储在一个字段中(TestNG 不会从头开始重新创建您的实例,因此该字段将保留其值)。
For example
例如
private int mResult;
@Test
public void f1() {
mResult = ...
}
@Test(dependsOnMethods = "f1")
public void f2() {
// use mResult
}
回答by Jorge Mu?oz
With the ITestContextobject. It's a object available globally at the Suite context and disponible via parameter in each @Test.
与ITestContext对象。它是在 Suite 上下文中全局可用的对象,可通过每个 @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);
// ...
}
回答by simendsjo
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.
每个单元测试都应该独立于其他测试,这样您就可以更容易地看到失败的地方。您可以使用辅助方法保存产品并返回 id 并从两个测试中调用它。

