首页 > 解决方案 > 使用 Beanshell 引用 testng.xml 中定义的参数

问题描述

我正在尝试使用一个参数来确定将运行我的 TestNG 套件中的哪一组测试。为此,我的 testng.xml 文件目前看起来像这样。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="Test">
        <parameter name="groupToRun" value="${valueFromJenkins}" />
        <method-selectors>
            <method-selector>
                <script language="beanshell"><![CDATA[
       return groups.containsKey(groupToRun);
     ]]></script>
            </method-selector>
        </method-selectors>
        <classes>
            <class name="main.java.CWV_Functional.CWV_Functionals" />
        </classes>
    </test>
</suite> 

这个想法是 groupToRun 的值是从触发此测试套件的 Jenkins 作业传递的。Beanshell 然后读取参数以确定应该运行哪个组。

问题是我不知道如何引用在 testng.xml 文件的参数标记中定义的参数,并且找不到任何说明如何执行此操作的文档。

有谁知道如何使用 Beanshell 来引用 testng.xml 文件中定义的参数?

标签: javaxmljenkinstestng

解决方案


从这里引用 TestNG 文档

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

  • java.lang.reflect.Method method:当前的测试方法。
  • org.testng.ITestNGMethod testngMethod:当前测试方法的描述。
  • java.util.Map<String, String> groups:当前测试方法所属的组图。

ITestNGMethod因此,您只需通过对象提取参数。

这是你如何做到的

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="54335160_suite" parallel="false" verbose="2" configfailurepolicy="continue">
  <parameter name="groupToRun" value="foo"/>
  <method-selectors>
    <method-selector>
      <script language="beanshell"><![CDATA[
        grpParameter = testngMethod.getXmlTest().getParameter("groupToRun");
       return groups.containsKey(grpParameter);
     ]]></script>
    </method-selector>
  </method-selectors>
  <test name="54335160_test">
    <classes>
      <class name="com.rationaleemotions.stackoverflow.qn54335160.Qn54335160Sample">
      </class>
    </classes>
  </test>
</suite>

推荐阅读