Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 308
simbo1905 Avatar asked Nov 14 '14 22:11

simbo1905


1 Answers

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

like image 197
Paul Butcher Avatar answered Sep 23 '22 18:09

Paul Butcher