[英]Test method that takes function literal in scala
我正在使用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])
我希望我的测试对传递给回调函数的'results'变量进行断言。 到目前为止,这就是我所拥有的:
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
}
}
}
}
}
但这是行不通的。 我已经在线检查过,似乎找不到解决方案。 任何想法将不胜感激。
您可以使用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
}
)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.