1

Hi I want to stub a method with specific parameters and to get the result with a helper method

val myDAOMock = stub[MyDao]

  (myDAOMock.getFoos(_:String)).when("a").returns(resHelper("a"))
//btw-is there a way to treat "a" as a parameter to the stubbed method and to the return ?
  (myDAOMock.getFoos(_:String)).when("b").returns(resHelper("b"))

def resHelpr(x:String) = x match{
case "a" => Foo("a")
case "b" => Foo("b")
}

but it seems that on my test I can capture only one since the 2nd test fails (regardless to the order that I run the tests )

"A stub test" must{
"return Foo(a)" in{
myDAOMock.getFoos("a")
}
"return Foo(b)" in{
myDAOMock.getFoos("b") //this one will fail on null pointer exception 
}

how can I improve my stubbing ?

igx
  • 4,101
  • 11
  • 43
  • 88

2 Answers2

1

I refactored your example a bit. I believe your issue is that the stubs for getFoos need to be defined within your tests.

import org.scalamock.scalatest.MockFactory
import org.scalatest._

class TestSpec extends FlatSpec with Matchers with MockFactory {
  val myDAOMock = stub[MyDao]
  val aFoo      = Foo("a")
  val bFoo      = Foo("b")

  def resHelper(x: String): Foo = {
    x match {
      case "a" => aFoo
      case "b" => bFoo
    }
  }

  "A stub test" must "return the correct Foo" in {
    (myDAOMock.getFoos(_: String)) when "a" returns resHelper("a")
    (myDAOMock.getFoos(_: String)) when "b" returns resHelper("b")

    assert(myDAOMock.getFoos("a") === aFoo)
    assert(myDAOMock.getFoos("b") === bFoo)
  }
}
Tim Graf
  • 11
  • 2
0

I think this was an issue in older versions of ScalaMock and should now be fixed in later versions, returning a better message instead of the NPE. The NPE happens as you re-used a mock in two cases. See http://scalamock.org/user-guide/sharing-scalatest/ how to do that safely.

Philipp
  • 967
  • 6
  • 16