我有一个单元测试,它测试了一些解决方案。但是这个测试代码也可以用于测试其他非常类似的解决方案。我想提出的是测试的代码是通用的被应用到这两种解决方案,如:使用类型参数写入函数
describe("when table contains all correct rows") {
it("should be empty") {
def check[T](func: T => List[Row]) = {
val tableGen = new TableGenerator()
val table: Vector[Row] = tableGen.randomTable(100)
.sortWith(_.time isBefore _.time).distinct
val result: List[Row] = func(table)
assert(result.isEmpty)
}
check(Solution.solution1)
check(Solution.solution2)
}
}
其中的解决方案有两类:
solution1: IndexedSeq[Row] => List[Row]
solution2: Seq[Row] => List[Row]
如何检查()函数必须写成能够做到这一点? 什么是最好的方法来写这个(可能以其他方式)与消除代码重复?
更新: 当我尝试编译这段代码,我得到类型不匹配的错误func(table)
:
Error:(36, 29) type mismatch;
found : table.type (with underlying type scala.collection.immutable.Vector[com.vmalov.tinkoff.Row])
required: T
val result = func(table)
为什么你认为你需要做什么吗?这个'check'函数应该已经可以做到这一点,并且没有重复的代码在你展示的内容中被消除。 –
一旦我试图编译我得到类型不匹配的错误:发现矢量[行],需要T(表我传递给func)。 第二个问题是关于可能存在另一个更好/更可靠的方法来抽象这样的事情。 – likern
你应该在问题中加上。 –