All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nordstrom.automation.junit.RuleChainWalker Maven / Gradle / Ivy

There is a newer version: 17.1.1
Show newest version
package com.nordstrom.automation.junit;

import java.lang.reflect.Field;
import java.util.List;

import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;

import com.google.common.base.Optional;
import com.nordstrom.common.base.UncheckedThrow;

/**
 * This is a static utility class that uses reflection to access the list of {@link TestRule} objects inside a
 * {@link RuleChain}.
 * 
 * @deprecated Use the order
 *             parameter of the {@literal @}Rule annotation instead of {@link RuleChain}.
 */
@Deprecated
public class RuleChainWalker {
    
    private RuleChainWalker() {
        throw new AssertionError("RuleChainWalker is a static utility class that cannot be instantiated");
    }
    
    /**
     * Get reference to an instance of the specified test rule type on the supplied rule chain.
     * 
     * @param  test rule type
     * @param ruleChain rule chain to be walked
     * @param ruleType test rule type
     * @return optional test rule instance
     */
    @SuppressWarnings("unchecked")
    public static  Optional getAttachedRule(RuleChain ruleChain, Class ruleType) {
        for (TestRule rule : getRuleList(ruleChain)) {
            if (rule.getClass() == ruleType) {
                return Optional.of((T) rule);
            }
        }
        return Optional.absent();
    }
    
    /**
     * Get the list of test rules from the specified rule chain.
     * 
     * @param ruleChain rule chain
     * @return list of test rules
     */
    @SuppressWarnings("unchecked")
    private static List getRuleList(RuleChain ruleChain) {
        Field ruleChainList;
        try {
            ruleChainList = RuleChain.class.getDeclaredField("rulesStartingWithInnerMost");
            ruleChainList.setAccessible(true);
            return (List) ruleChainList.get(ruleChain);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            throw UncheckedThrow.throwUnchecked(e);
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy