我有一個單元測試,它測試了一些解決方案。但是這個測試代碼也可以用於測試其他非常類似的解決方案。我想提出的是測試的代碼是通用的被應用到這兩種解決方案,如:使用類型參數寫入函數
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
你應該在問題中加上。 –