简体   繁体   中英

Test method that takes function literal in scala

I am using specs2 to test the following 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])

I want my test to assert on the 'results' variable passed into the callback function. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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