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!

Paul Butcher
  • 10,722
  • 3
  • 40
  • 44
simbo1905
  • 6,321
  • 5
  • 58
  • 86

1 Answers1

24

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

Paul Butcher
  • 10,722
  • 3
  • 40
  • 44
  • 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? – simbo1905 Nov 15 '14 at 08:25
  • 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. – Paul Butcher Nov 15 '14 at 09:57
  • 1
    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? – Daryl Odnert Jan 24 '15 at 00:19