【发布时间】:2016-09-30 12:33:35
【问题描述】:
我有一个单元测试,它测试一些解决方案。但是这个测试代码也可以用于测试其他非常相似的解决方案。我想要的是测试代码是通用的,适用于两种解决方案,如下所示:
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]
必须如何编写 check() 函数才能做到这一点? 在消除代码重复的情况下,编写这个(可能是其他方式)的最佳方法是什么?
更新:
当我尝试编译此代码时,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 的表)。第二个问题是关于可能有另一种更好/更受欢迎的方法来抽象这些东西。
-
你应该在问题中添加它。
-
好的,抱歉,错过了一点。
-
我建议您添加一条消息以帮助识别测试,否则如果测试失败,您将无法很快知道两者中的哪一个。
标签: scala generics scalatest type-parameter