我想根据某些条件在运行时将组设置为特定的@Test 方法
假设我有以下类(class)
public class MyTest1{
@Test
public void test1(){
System.out.println("test1 called");
}
}
public class MyTest2{
@Test(groups={"group1"})
public void test2(){
System.out.println("test2 called");
}
@Test(groups={"group2"})
public void test3(){
System.out.println("test3 called");
}
}
现在在运行测试时,我在命令行中向 TestNG 发送“-groups group1”或“-groups group2”。所以 testng 根据传递的组名运行 test2() 或 test3() 。现在我的要求是运行不应附加任何组的 test1()。无论我向 testng runner 提供什么组,这个 test1() 都应该每次都运行。我尝试实现 IAlterSuiteListener 的 alter 方法,但我无法获得所有测试方法,包括不考虑运行的方法。所以我无法在运行时设置组名。
那么有没有其他方法可以在运行时将组设置为@Test 方法(没有定义组)?
最佳答案
您也许应该开始探索 TestNG 为此目的提供给您的方法选择的 beanshell 方式。
前段时间我写了一篇博文,讨论如何在 TestNG 中使用 Beanshell 表达式。您可以阅读更多相关信息 here并引用 TestNG 官方文档 here .
引用TestNG文档,
TestNG defines the following variables for your convenience:
- java.lang.reflect.Method method: the current test method.
- org.testng.ITestNGMethod testngMethod: the current test method.
- java.util.Map groups: a map of the groups the current test method belongs to.
因此,就您的示例而言,我继续创建一个如下所示的套件 xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="1265_Suite" parallel="false" verbose="2">
<test name="92" parallel="false" preserve-order="true">
<method-selectors>
<method-selector>
<script language="beanshell">
<![CDATA[whatGroup = System.getProperty("groupToRun");
(groups.containsKey(whatGroup) || testngMethod.getGroups().length ==0);
]]>
</script>
</method-selector>
</method-selectors>
<classes>
<class name="com.rationaleemotions.stackoverflow.MyTest1"/>
<class name="com.rationaleemotions.stackoverflow.MyTest2"/>
</classes>
</test>
</suite>
然后我使用 maven 通过命令提示符运行它,如下所示:(测试类基本上是您在问题中共享的内容)
mvn clean test -DsuiteXmlFile=dynamic_groups.xml -DgroupToRun=group2
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
...
... TestNG 6.11 by Cédric Beust (cedric@beust.com)
...
test1 called
test3 called
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.377 sec - in TestSuite
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
关于java - 如何使用 TestNG 将测试组动态设置为 @Test 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44247270/