简体   繁体   English

在scala中采用函数文字的测试方法

[英]Test method that takes function literal in scala

I am using specs2 to test the following class 我正在使用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])

I want my test to assert on the 'results' variable passed into the callback function. 我希望我的测试对传递给回调函数的'results'变量进行断言。 So far, this is what I have: 到目前为止,这就是我所拥有的:

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
        }
      }
    }
  }
}

But this does not work. 但这是行不通的。 I've checked online and can't seem to find a solution. 我已经在线检查过,似乎找不到解决方案。 Any ideas would be much appreciated. 任何想法将不胜感激。

You can mock your callback with Mockito: 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM