I am working with JunitRules RuleChain and Kotlin. I am new to both and have two classes that do the exact same thing, the only difference being the rule chain.
The first class looks like this :
class BaseActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>
) : TestRule by RuleChain.outerRule(CustomRuleOne).around(activityRule) {
// do something
}
I require another class that does the exact same thing as BaseActivityTestRule
but the delegate is different.
Example :
class ExtendedActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>
) : TestRule by RuleChain.outerRule(CustomRuleOne).around(CustomRuleTwo).around(activityRule) {
// do something
}
How can I accomplish this without duplicating code blocks?
Just pass a boolean parameter to your constructor and use it to create the basic or extended TestRule
:
fun <T> createTestRule(activityRule: ActivityRule<T>, extended: Boolean) =
if(extended)
RuleChain.outerRule(CustomRuleOne).around(CustomRuleTwo).around(activityRule)
else
RuleChain.outerRule(CustomRuleOne).around(activityRule)
class ActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>,
extended: Boolean = false
) : TestRule by createTestRule(activityRule, extended) {
// do something
}