【问题标题】:scalamock stubbing method with specific parameters fails on null具有特定参数的 scalamock 存根方法在 null 上失败
【发布时间】:2017-03-24 20:23:59
【问题描述】:

您好,我想使用特定参数对方法进行存根,并使用辅助方法获取结果

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 
}

如何改进我的存根?

【问题讨论】:

    标签: scala scalatest scalamock


    【解决方案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)
      }
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        相关资源
        最近更新 更多