首页 > 解决方案 > TestNG 在运行 pom.xml 中提到的所有测试套件之前运行一次

问题描述

我在 Surefire 插件中设置了多个 testng.xml 文件,以便我可以使用 Maven 从命令提示符运行自动化测试

现在,我面临一个问题。我如何设置它suiteListener以执行一些任务,例如删除从上次运行中捕获的文件和屏幕截图。(一次运行包含多个套件文件)

现在发生的是第一个测试套件运行并捕获屏幕截图并创建日志。当第二个套件运行时,它会清除之前捕获的屏幕截图和日志,并为此运行创建一个新的屏幕截图。

有没有一种方法可以让这个方法在每次运行时运行一次,不是在每个测试套件之前运行一次。

import java.io.IOException;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import com.company.appium.base.BaseTest;
public class suiteListener extends BaseTest implements ISuiteListener {

    @Override
    public void onStart(ISuite suite) {
        // This method will be executed before Test Suite run
        try {
            deletePreviousScreenShots();
            System.out.println("Inside onStart of suiteListener");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Before starting test suite: " + suite.getName() + " in onStart() method");
    }
    @Override
    public void onFinish(ISuite suite) {
        // This method will be executed at the end of the Test Suite run
        System.out.println("After executing the test suite: " + suite.getName() + " in onFinish() method");
    }
} 

标签: javamaventestngtestng.xml

解决方案


因为我不确定是否suiteListener为每个套件运行创建了一个新实例。ISuite suite因此,只有当通过参数接收到的套件名称与您提供的“第一个”xml 套件文件匹配时,您才能继续删除。

public class suiteListener extends BaseTest implements ISuiteListener {

    private static final String firstTest = "suite1";
    @Override
    public void onStart(ISuite suite) {
        if(!suite.getName().equals(firstTest)) {
            return;
        }

        // rest of the code
    }
}

推荐阅读