001
014
015 package com.liferay.portal.kernel.test.rule;
016
017 import java.util.Arrays;
018 import java.util.Comparator;
019 import java.util.HashSet;
020 import java.util.Set;
021
022 import org.junit.rules.TestRule;
023 import org.junit.runner.Description;
024 import org.junit.runners.model.Statement;
025
026
029 public class AggregateTestRule implements TestRule {
030
031 public AggregateTestRule(boolean sort, TestRule... testRules) {
032 if (testRules == null) {
033 throw new NullPointerException("Test rules is null");
034 }
035
036 if (testRules.length < 2) {
037 throw new IllegalArgumentException(
038 "Rule number " + testRules.length + " is less than 2");
039 }
040
041 _testRules = testRules;
042
043 if (sort) {
044 Arrays.sort(_testRules, _testRuleComparator);
045 }
046 }
047
048 public AggregateTestRule(TestRule... testRules) {
049 this(true, testRules);
050 }
051
052 @Override
053 public Statement apply(Statement statement, Description description) {
054 for (int i = _testRules.length - 1; i >= 0; i--) {
055 statement = _testRules[i].apply(statement, description);
056 }
057
058 return statement;
059 }
060
061 private static final String[] _ORDERED_RULE_CLASS_NAMES = new String[] {
062 HeapDumpTestRule.class.getName(), CodeCoverageAssertor.class.getName(),
063 NewEnvTestRule.class.getName(),
064 "com.liferay.portal.test.rule.PortalExecutorManagerTestRule",
065 "com.liferay.portal.test.rule.LiferayIntegrationTestRule",
066 "com.liferay.portal.test.rule.MainServletTestRule",
067 "com.liferay.portal.test.rule.PersistenceTestRule",
068 TransactionalTestRule.class.getName(),
069 SynchronousDestinationTestRule.class.getName(),
070 "com.liferay.portal.test.rule.SynchronousMailTestRule",
071 "com.liferay.portlet.documentlibrary.webdav." +
072 "WebDAVEnvironmentConfigTestRule",
073 "com.liferay.portal.test.rule.SyntheticBundleRule"
074 };
075
076 private static final Comparator<TestRule> _testRuleComparator =
077 new Comparator<TestRule>() {
078
079 @Override
080 public int compare(TestRule testRule1, TestRule testRule2) {
081 return getIndex(testRule1.getClass()) -
082 getIndex(testRule2.getClass());
083 }
084
085 private int getIndex(Class<?> testRuleClass) {
086 Set<String> testRuleClassNames = new HashSet<>();
087
088 while (TestRule.class.isAssignableFrom(testRuleClass)) {
089 testRuleClassNames.add(testRuleClass.getName());
090
091 testRuleClass = testRuleClass.getSuperclass();
092 }
093
094 for (int i = 0; i < _ORDERED_RULE_CLASS_NAMES.length; i++) {
095 if (testRuleClassNames.contains(
096 _ORDERED_RULE_CLASS_NAMES[i])) {
097
098 return i;
099 }
100 }
101
102 throw new IllegalArgumentException(
103 "Unknown test rule class : " + testRuleClass);
104 }
105
106 };
107
108 private final TestRule[] _testRules;
109
110 }