4

I'm trying to follow this doc - scalatest with scala-mock to mock the function and check if it has been called

class AggregateSpec extends FlatSpec with Matchers with MockFactory {

 val data = Seq("This", "is", "something", "I", "would", "like", "to", "know")

"combop function" should "BE called for par collection" in {

    val mockCombop = mockFunction[Int, Int, Int]

    val parData = data.par

    val result: Int = parData.aggregate(0)(
      seqop = (acc, next) => acc + next.length,
      combop = mockCombop
    )

    result should === (31)
    mockCombop.expects(*, *).atLeastOnce()

  }
}

As result:

> [info] - should BE called for non-par collection *** FAILED *** [info]
> Unexpected call: MockFunction2-1(4, 2) [info]    [info]   Expected:
> [info]   inAnyOrder { [info]    [info]   } [info]    [info]   Actual:
> [info]     MockFunction2-1(9, 1) [info]     MockFunction2-1(2, 4)
> [info]     MockFunction2-1(4, 2) [info]     MockFunction2-1(5, 4)
> (Option.scala:121)

Why? How to make it pass with scalatest + scala-mock ?

--

As deps I use:

   libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1",
    libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test",
    libraryDependencies += "org.scalamock" %% "scalamock-scalatest-support" % "3.5.0"
ses
  • 13,174
  • 31
  • 123
  • 226

1 Answers1

5

You need to call mockCombop.expects before mockCombop gets called, not after:

"combop function" should "BE called for par collection" in {
  val mockCombop = mockFunction[Int, Int, Int]

  val parData = data.par

  mockCombop.expects(*, *).atLeastOnce()

  val result: Int = parData.aggregate(0)(
    seqop = (acc, next) => acc + next.length,
    combop = mockCombop
  )

  result should === (31)
}
  • Yeah. Good catch. Only thing is that the bottom much nicer place for 'expect' to be than the top. – ses May 07 '17 at 22:57
  • you can use Record-then-Verify style, as described here: http://scalamock.org/user-guide/mocking_style/ – Philipp May 08 '17 at 15:25
  • https://github.com/Sergey80/scala-samples/blob/master/algorithms/src/test/scala/tests/AggregateSpec.scala – ses May 12 '17 at 02:22