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

1

6

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!

Korean answered 14/11, 2014 at 22:32 Comment(0)
G
26

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

Gina answered 15/11, 2014 at 1:2 Comment(3)
seems odd that it has two different objects rather than one; at first glance it seems that mock is write-only. am i missing something as to why this is?Korean
Sorry, I'm not sure I understand what you mean by "write-only"? If there is a way to have a single type of fake object support both mocking styles, I'd love to hear it, but it's not clear to me how this could be achieved right now.Gina
It would be great if there were some way for this type of problem to be caught at compile time rather than at runtime. But the compile-time type of the mock[SomeTrait] and stub[SomeTrait] expressions must be SomeTrait. If it weren't, ScalaMock wouldn't be doing what a mocking framework is supposed to do. However, I wonder if it might be possible for the ScalaMock framework to identify at runtime when the programmer has made this mistake and put a helpful suggestion in the Exception's message?Ure

© 2022 - 2024 — McMap. All rights reserved.