Testng how to pass parameter to the listener

2019-09-13 02:02发布

问题:

I would like to know a way to pass a parameter inside a listener eater from my suite.xml or by the code itself

I need this in parallel test to know exactly on which device I'm running a test in order to make some reports

this is an example of what I have / wish to achieve

the suite file

<suite name="SearchButton" parallel="tests" thread-count="5">
    <test name="SamsungS6">
        <parameter name="deviceUDID"  value="04157df40862d02f"/>
        <classes>
            <class name="MyTestScenario"/>
        </classes>
    </test>
</suite>

or

@Test
public void researchText (){
    String DeviceUDID = "1234";
}

I want to be able to find device UDID in my listener

public void onTestSkipped(ITestResult result) {
    System.out.println("My deviceUDID ");
}

I tried to find it with

System.getProperty("deviceUDID") // or
result.getAttribute() // or
result.getParameters()

without success

Any idea on how to do it ?

回答1:

get* methods cannot work if you don't use a set* somewhere else.

I see 2 options:

  1. From the test by setting data in the ITestContext (ITestResult#getTestContext()) which is injectable. See the related documentation.
  2. From the listener with an annotation metadata on the test method (ie: @UDID("1234")). But it may be more difficult to use in the test itself if you want avoid duplication.

According your example:

@Test
public void researchText(ITestContext context){
    String DeviceUDID = "1234";
    context.setAttribute("UDID", DeviceUDID)
}

public void onTestSkipped(ITestResult result) {
    System.out.println("My deviceUDID " + result.getTestContext().getAttribute("UDID"));
}

or

<suite name="SearchButton" parallel="tests" thread-count="5">
    <test name="SamsungS6">
        <parameter name="deviceUDID"  value="04157df40862d02f"/>
        <classes>
            <class name="MyTestScenario"/>
        </classes>
    </test>
</suite>

@Parameters({ "deviceUDID" })
@Test
public void researchText (String DeviceUDID, ITestContext context){
    context.setAttribute("UDID", DeviceUDID)
}

public void onTestSkipped(ITestResult result) {
    System.out.println("My deviceUDID " + result.getTestContext().getAttribute("UDID"));
}


回答2:

I did finally found a way to do it. It can maybe be considered as a work around but it does the job.

In the ITestListener listener I've seen that we have a onStart method that allows me to access the parameter from the .xml file

    deviceUDID = context.getCurrentXmlTest().getParameter("deviceUDID");

And now that I have it inside the listener I just had to save it in variable and access it in the onTestSkipped method