我正在使用JunitRules RuleChain和Kotlin。我对这两个类都是新手,有两个类做着完全相同的事情,唯一的区别是规则链。
第一类看起来是这样的:
class BaseActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>
) : TestRule by RuleChain.outerRule(CustomRuleOne).around(activityRule) {
// do something
}
我需要另一个类来做与BaseActivityTestRule
完全相同的事情,但委托不同。
示例:
class ExtendedActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>
) : TestRule by RuleChain.outerRule(CustomRuleOne).around(CustomRuleTwo).around(activityRule) {
// do something
}
如何在不复制代码块的情况下实现这一点?
只需将布尔参数传递给构造函数,并使用它来创建基本或扩展的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
}
回答我自己的问题。最后,我对功能进行了抽象,并创建了两个具有不同签名的独立类来扩展抽象类。
示例:
abstract class BaseActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>){
// Do Something
}
然后扩展它:
class ExtendedActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>): BaseActivityTestRule<T>(activityRule), TestRule by Delegate
对于后续实施:
class DifferentActivityTestRule<T : Activity>(
private val activityRule : ActivityRule<T>): BaseActivityTestRule<T>(activityRule), TestRule by SomeOtherDelegate