Java tutorial
/** * Copyright (c) 2005-2011 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: GroupsUtils.java 516 2009-10-02 13:55:33Z calvinxiu $ */ package cn.hxh.springside.test.groups; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; import org.junit.Ignore; import org.junit.Test; import org.junit.internal.runners.model.EachTestNotifier; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; /** * TestNG GroupsTestRunner. * * ??, ?. * * Runner?@Groups, JVM??-Dtest.groups=xxx,yyy?. * -Dtest.groups. * ???Runner. * * ?, ?JUnit 4.4. * * @author freeman * @author calvin */ public class GroupsTestRunner extends BlockJUnit4ClassRunner { /** JVM?-D????. */ public static final String PROPERTY_NAME = "test.groups"; private static List<String> groups; public GroupsTestRunner(Class<?> klass) throws InitializationError { super(klass); } //--?Runner--// /** * ?Class. */ @Override public void run(RunNotifier notifier) { if (!shouldRun(getTestClass().getJavaClass())) { EachTestNotifier testNotifier = new EachTestNotifier(notifier, getDescription()); testNotifier.fireTestIgnored(); return; } super.run(notifier); } /** * ?. */ @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { if (!shouldRun(method.getMethod())) { Description description = describeChild(method); EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestIgnored(); return; } super.runChild(method, notifier); } //-- /?? --// /** * ???. * ??Groupstrue. */ public static boolean shouldRun(Class<?> testClass) { Method[] methods = testClass.getMethods(); for (Method method : methods) { if (method.getAnnotation(Test.class) != null && method.getAnnotation(Ignore.class) == null && shouldRun(method)) { return true; } } return false; } /** * ??Groups?. * @Groups?GroupsALL@Groupstrue. */ public static boolean shouldRun(Method testMethod) { //?Groups if (groups == null) { initGroups(); } //groupstrue if (groups.contains(Groups.ALL)) { return true; } //?Groups annotation, Groups??true. Groups groupsAnnotation = testMethod.getAnnotation(Groups.class); if ((groupsAnnotation == null) || groups.contains(groupsAnnotation.value())) { return true; } return false; } /** * ???test.groups, group?. * eg. java -Dtest.groups=Daily,Nightly * Groups.ALL. */ protected static void initGroups() { String groupsProperty = System.getProperty(PROPERTY_NAME); //??test.groups,?property?. if (StringUtils.isBlank(groupsProperty)) { groupsProperty = Groups.ALL; } groups = Arrays.asList(groupsProperty.split(",")); } }