我正在与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
}
如何在不复制代码块的情况下完成此任务?
答案 0 :(得分:0)
只需将布尔参数传递给构造函数,然后使用它创建基本的或扩展的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
}
答案 1 :(得分:0)
回答我自己的问题。最后,我对功能进行了抽象,并创建了两个具有不同签名的独立类,以扩展抽象类。
示例:
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