如何在不更改testng.xml文件的情况下限制TestNG类中的@Test方法

时间:2017-08-10 09:28:53

标签: testng

我想从一个具有多个@Test方法

的类中只执行一个@test方法

下面是我编写的示例代码,但它运行ADC类中的所有方法 TestNG testng = new TestNG();         Class [] classes = new Class [] {ABC.class};

moment().format('LT').replace(/(:|\.|e)[0-9]{2}/, '');

有人能告诉我这个代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

这是一个完整的示例,可让您从特定类(或)中从给定包中的一个或多个类中手工挑选方法。

import org.testng.TestNG;
import org.testng.internal.ClassHelper;
import org.testng.internal.PackageUtils;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class TestRunner {


    /**
     * This method accepts two parameters both via JVM arguments.
     * <ul>
     * <li>type - Specified as -Dtype. It can either begin with "package:" (or) it can begin with "class:"</li>.
     * <li>methodname - Specified as -Dmethodname. Represents the method name which is to be filtered.</li>
     * </ul>
     */
    public static void main(String[] args) throws IOException {
        List<String> empty = Collections.emptyList();
        String filter = System.getProperty("type", "package:com.rationaleemotions.stackoverflow.qn45436872");
        String name = System.getProperty("methodname", "SomeTest");
        FilterType type = FilterType.parse(filter);
        String filterValue = filter.split(":")[1];
        final Set<Method> methods = new HashSet<>();
        Predicate<String> notObjectClass = (String className) -> !className.equals(Object.class.getName());
        switch (type) {
            case PACKAGE:
                String[] classes = PackageUtils.findClassesInPackage(filterValue, empty, empty);
                if (name.equals("*")) {
                    //The value "*" indicates that all methods are to be included.
                    Arrays.stream(classes).filter(notObjectClass).forEach(clazz -> {
                        Class<?> clz = ClassHelper.forName(clazz);
                        methods.addAll(ClassHelper.getAvailableMethods(clz));
                    });
                } else {
                    Arrays.stream(classes).filter(notObjectClass).forEach(clazz -> {
                        Class<?> clz = ClassHelper.forName(clazz);
                        Set<Method> filteredMethods = methodsMatchingName(clz, name);
                        methods.addAll(filteredMethods);
                    });
                }
                break;
            case CLASS:
            default:
                Class<?> clazz = ClassHelper.forName(filterValue);
                if (name.equals("*")) {
                    //The value "*" indicates that all methods are to be included.
                    methods.addAll(ClassHelper.getAvailableMethods(clazz));
                } else {
                    Set<Method> filteredMethods = methodsMatchingName(clazz, name);
                    methods.addAll(filteredMethods);
                }

        }

        Map<Class<?>, List<Method>> map = methods.stream().collect(Collectors.groupingBy(Method::getDeclaringClass));
        TestNG testNG = new TestNG();
        XmlSuite xmlSuite = new XmlSuite();
        xmlSuite.setName("sample_suite");
        XmlTest xmlTest = new XmlTest(xmlSuite);
        xmlTest.setName("sample_test");


        List<XmlClass> xmlClasses = new ArrayList<>();

        map.entrySet().stream()
                .filter(classListEntry -> !classListEntry.getKey().equals(Object.class))
                .forEach(entry -> {
                    XmlClass xmlClass = new XmlClass(entry.getKey());
                    entry.getValue().forEach(m -> xmlClass.getIncludedMethods().add(new XmlInclude(m.getName())));
                    xmlClasses.add(xmlClass);
                });
        xmlTest.setClasses(xmlClasses);
        testNG.setXmlSuites(Collections.singletonList(xmlSuite));
        System.err.println("The suite file that will be used");
        System.err.println(xmlSuite.toXml());
        testNG.run();
    }

    private static Set<Method> methodsMatchingName(Class<?> clazz, String name) {
        return ClassHelper.getAvailableMethods(clazz)
                .stream()
                .filter(m -> m.getName().equals(name))
                .collect(Collectors.toSet());
    }

    private enum FilterType {
        CLASS("class:"),
        PACKAGE("package:");

        FilterType(String type) {
            this.type = type;
        }

        private String type;

        public static FilterType parse(String type) {
            if (type == null || type.trim().isEmpty()) {
                throw new IllegalArgumentException("Type cannot be null (or) empty.");
            }
            return Arrays.stream(values())
                    .filter(each -> type.startsWith(each.type))
                    .findFirst().orElseThrow(() ->
                            new IllegalArgumentException("Unknown type specified"));
        }
    }
}