1

嗨我想存根具有特定参数的方法并使用辅助方法获取结果

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")
}

但似乎在我的测试中我只能捕获一个,因为第二次测试失败(不管我运行测试的顺序)

"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 
}

我怎样才能改善我的存根?

4

2 回答 2

1

我对您的示例进行了一些重构。我相信您的问题是getFoos需要在您的测试中定义存根。

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)
  }
}
于 2016-01-30T23:47:14.667 回答
0

我认为这在旧版本的 ScalaMock 中是一个问题,现在应该在以后的版本中修复,返回更好的消息而不是 NPE。NPE 发生在您在两种情况下重新使用模拟时。请参阅http://scalamock.org/user-guide/sharing-scalatest/如何安全地做到这一点。

于 2017-03-24T12:23:59.037 回答