在scala中采用函数文字的测试方法
Test method that takes function literal in scala
我正在使用 specs2 测试以下 class
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
}
)
}
}
}
我正在使用 specs2 测试以下 class
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
}
)
}
}
}