您好我想使用特定参数存根方法并使用辅助方法获取结果
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
}
如何改善我的存根?
答案 0 :(得分: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)
}
}
答案 1 :(得分:0)
我认为这是旧版ScalaMock中的问题,现在应该在以后的版本中修复,返回更好的消息而不是NPE。在两种情况下重新使用模拟时会发生NPE。 请参见http://scalamock.org/user-guide/sharing-scalatest/如何安全地执行此操作。