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.HypersonicServerTestRule",
068 "com.liferay.portal.test.rule.PersistenceTestRule",
069 TransactionalTestRule.class.getName(),
070 SynchronousDestinationTestRule.class.getName(),
071 "com.liferay.portal.test.rule.SynchronousMailTestRule",
072 "com.liferay.document.library.webdav.test." +
073 "WebDAVEnvironmentConfigTestRule",
074 "com.liferay.portal.test.rule.SyntheticBundleRule"
075 };
076
077 private static final Comparator<TestRule> _testRuleComparator =
078 new Comparator<TestRule>() {
079
080 @Override
081 public int compare(TestRule testRule1, TestRule testRule2) {
082 return getIndex(testRule1.getClass()) -
083 getIndex(testRule2.getClass());
084 }
085
086 private int getIndex(Class<?> testRuleClass) {
087 Set<String> testRuleClassNames = new HashSet<>();
088
089 while (TestRule.class.isAssignableFrom(testRuleClass)) {
090 testRuleClassNames.add(testRuleClass.getName());
091
092 testRuleClass = testRuleClass.getSuperclass();
093 }
094
095 for (int i = 0; i < _ORDERED_RULE_CLASS_NAMES.length; i++) {
096 if (testRuleClassNames.contains(
097 _ORDERED_RULE_CLASS_NAMES[i])) {
098
099 return i;
100 }
101 }
102
103 throw new IllegalArgumentException(
104 "Unknown test rule class : " + testRuleClass);
105 }
106
107 };
108
109 private final TestRule[] _testRules;
110
111 }