ScalaMock mocking a trait gives "MockFunction1 cannot be cast to StubFunction1"

7.8k views Asked by At

The following code:

import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpec

trait SomeTrait {
  def getLongByInt(int: Int): Long
}

class TestScalaMock extends FlatSpec with MockFactory {
  "Scala Mock" should "mock my trait" in {
    val someTrait = mock[SomeTrait]
    (someTrait.getLongByInt _) when (1) returns 2L
    assert(2L == someTrait.getLongByInt(1))
  }
}

Gives me a runtime error org.scalamock.MockFunction1 cannot be cast to org.scalamock.StubFunction1. My project dependencies are:

scalaVersion := "2.11.0"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.3.7",
  "com.typesafe.akka" %% "akka-testkit" % "2.3.7",
  "org.scalatest" % "scalatest_2.11" % "2.2.1" % "test",
  "org.scalamock" %% "scalamock-scalatest-support" % "3.2" % "test"
  )

Any ideas? Thanks!

1

There are 1 answers

3
Paul Butcher On BEST ANSWER

ScalaMock supports two different styes—expectation-first and record-then-verify (Mockito-style).

For expectation-first, use mock to create the fake object and expects to set expectations.

For record-then-verify, use stub to create the fake object, when to setup return values and verify to verify calls.

In your code you're using mock (expectations-first) together with when (record-then-verify). Use expects instead, and you should be fine.

(note, you can mix different styles within a single test, but not for a single fake object).