嗨,我想用特定参数存根一个方法,并使用辅助方法获得结果
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
}
如何改善我的存根?
我稍微重构了一下你的示例。 我相信您的问题是需要在测试中定义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)
}
}
我认为这是旧版本的 ScalaMock 中的一个问题,现在应该在更高版本中修复,返回更好的消息而不是 NPE。NPE 发生在您在两种情况下重复使用模拟时。请参阅 http://scalamock.org/user-guide/sharing-scalatest/如何安全地执行此操作。