2016-02-20 31 views
-1

我使用specs2測試下面的類測試方法,它的功能文字斯卡拉

class ConstraintSolver { 
    def solve(solver: Solver)(callback: (ConstraintSolution) => Unit) = { 
    val results = solver.solve() 
    callback(ConstraintSolution(true, results)) 
    } 
} 

case class ConstraintSolution(isSuccessful: Boolean, results: Map[String, Variable]) 

我想我的測試斷言的「結果」變量傳遞到回調函數。到目前爲止,這是我有:

class ConstraintSolverSpec extends Specification { 
    "ConstraintSolver" should { 
    "solve a matching problem and report the solution" in { 
     val constraintSolver = new ConstraintSolver() 

     val solverWithCapacityConstraints = .... 
     constraintSolver.solve(solverWithCapacityConstraints) { 
     constraintSolution => { 
      constraintSolution.isSuccessful shouldEqual true 
     } 
     } 
    } 
    } 
} 

但這不起作用。我在網上查過,似乎無法找到解決方案。任何想法將不勝感激。

+0

你能解釋一下「不工作」? –

+0

如何嘲笑你的回調? –

+0

@Łukasz我得到錯誤「無法找到類型爲org.specs2.main.CommandLineAsResult [Unit]」的證據參數的隱式值。認爲它需要在測試的主體中聲明,所以我在底部添加了「成功」,並修復了它。 – Austen

回答

2

你可以嘲笑的Mockito你的回調:

class ConstraintSolverSpec extends Specification with Mockito { 
    "ConstraintSolver" should { 
    "solve a matching problem and report the solution" in { 
     val constraintSolver = new ConstraintSolver() 
     val callbackMock = mock[(ConstraintSolution) => Unit] 

     val solverWithCapacityConstraints = .... 
     constraintSolver.solve(solverWithCapacityConstraints)(callbackMock) 

     // now check 
     there was one(callbackMock).apply(
     beLike[ConstraintSolution] { case solution => 
      solution.isSuccessful should beTrue 
     } 
    ) 
    } 
    } 
}