我正在使用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 :(得分: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
}
)
}
}
}