How to run the specified testNG
case by code? The following code:
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();
}
}
This would run both the test cases. How to specifically run "test2" only?
Expected output:
test2 ************
CodePudding user response:
You can use the classes prefixed with Xml
to achieve this:
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"));
Now create xml suite and xml test:
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));
Final create TestNG
object:
TestNG t = new TestNG();
t.setXmlSuites(List.of(suite));
t.run();
Note: List.of
is a method available only in java 9 or above. If you are using a lower version, then you may use java.util.Arrays.asList
CodePudding user response:
You can do that by adding a method interceptor like this:
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());
}
}