如何通过代码运行指定的testng案例?

How to run the specified testng case by code?

如何通过代码运行指定的testNG case?以下代码:

public class TestNGTest {

    @Test
    public void test() {
        System.out.println("test  ########");
    }

    @Test
    public void test2() {
        System.out.println("test2 ************");
    }

    public static void main(String[] args) throws Exception {
        TestNG testSuite = new TestNG();

        testSuite.setTestClasses(new Class[] { TestNGTest.class });
        testSuite.setDefaultSuiteName("setDefaultSuiteName");
        testSuite.setDefaultTestName("setDefaultTestName");
        testSuite.run();
    }
}

这将 运行 两个测试用例。如何具体 运行 "test2" only?

预期输出:

test2 ************

您可以使用带有 Xml 前缀的 类 来实现:

XmlClass xmlClass = new XmlClass(TestNGTest.class.getName());
// now mention the methods to be included. You may use setExcludedMethods depending on the requirement.
XmlInclude method = new XmlInclude("test2");
xmlClass.setIncludedMethods(List.of(method));
// or xmlClass.setExcludedMethods(List.of("test"));

现在创建 xml 套件和 xml 测试:

XmlSuite suite = new XmlSuite();
suite.setName("suite");

XmlTest test = new XmlTest(suite);
// internally, the test method is also added to the suite object
test.setName("sample");
test.setXmlClasses(List.of(xmlClass));

最终创建 TestNG 对象:

TestNG t = new TestNG();
t.setXmlSuites(List.of(suite));
t.run();

注意: List.of 是java 9 及以上版本才有的方法。如果您使用的是较低版本,那么您可以使用 java.util.Arrays.asList

您可以通过添加这样的方法拦截器来做到这一点:

public class TestNGTest implements IMethodInterceptor {

    @Test
    public void test() {

        System.out.println("test  ########");
    }

    @Test
    public void test2() {

        System.out.println("test2 ************");
    }

    public static void main(String[] args) throws Exception {
        TestNG testSuite = new TestNG();

        testSuite.setTestClasses(new Class[] { TestNGTest.class });
        testSuite.setMethodInterceptor(new TestNGTest());
        testSuite.setDefaultSuiteName("setDefaultSuiteName");
        testSuite.setDefaultTestName("setDefaultTestName");
        testSuite.run();
    }

    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        return methods
                .stream()
                .filter(iMethodInstance -> "test2".equals(iMethodInstance.getMethod().getMethodName()))
                .collect(Collectors.toList());
    }
}