如何使用TestNG动态地将测试组设置为@Test方法?

时间:2017-05-29 16:51:53

标签: java testing testng

我希望在运行时根据某些条件将组设置为特定的@Test方法

假设我有以下类

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");
  }
}

现在,在运行测试时,我正在发送" -groups group1"或" -groups group2"在命令行中使用TestNG。所以testng运行test2()或test3(),具体取决于传递的组名。现在我的要求是运行test1(),不应该附加任何组。无论我为testng跑者提供什么组,每次都应该运行test1()。我尝试使用IAlterSuiteListener的alter方法,但是我无法获得所有测试方法,包括不考虑运行的方法。所以我无法在运行时设置组名。

那么还有其他方法可以在运行时将组设置为@Test方法(没有定义组)吗?

2 个答案:

答案 0 :(得分:1)

您应该开始探索TestNG为此目的提供的方法选择的beanshell方法。

有时回来我写了一篇博文,讲述了如何在TestNG中使用Beanshell表达式。您可以阅读更多相关信息here,并参阅官方的TestNG文档here

引用TestNG文档,

  

为方便起见,TestNG定义了以下变量:

     
      
  • java.lang.reflect.Method方法:当前的测试方法。
  •   
  • org.testng.ITestNGMethod testngMethod:当前的测试方法。
  •   
  • java.util.Map groups:当前测试方法所属的组的映射。
  •   

所以只用你的例子,我就开始创建一个类似于下面的套件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

答案 1 :(得分:0)

如果要指定组,则没有直接的方法。但是,还有另外两种方法可以做到这一点。

  1. 您可以在名为“nogroups”的组中标记所有没有组的测试,并在运行时包含该组 或
  2. 如果您已经拥有大量的测试,那么请编写一个Annotation Transformer,它基本上会添加此组中没有组的案例 - 下面的示例。编写变换器也可以帮助您以编程方式控制边缘情况。
  3. public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { if (annotation.getGroups().length == 0) { annotation.setGroups(new String[]{"noGroups"}); } }

相关问题