Spec2:将第二个参数参数传递给模拟方法调用

时间:2014-10-13 19:50:40

标签: scala unit-testing mockito matcher specs2

我有一个带有3个参数的模拟服务。我如何访问第二个参数?

mockedService.invoke(arg1, arg2, arg3) answers {
  (params, mock) => {
     //Do something with params.arg2 to the value that is returned from the invocation
  }
}

在文档中,他们声明"方法参数的数组将被传递" 如何访问第二个参数(在这种情况下为arg2)?我使用params投射List[Any]吗?

由于

1 个答案:

答案 0 :(得分:4)

您需要将参数匹配为Array,如下所示:

import org.specs2.Specification
import org.specs2.mock.Mockito

class TestSpec extends Specification with Mockito { def is = s2"""
  test $e1
"""

  def e1 = {
    val mockedService = mock[Service]
    mockedService.invoke(1, 2, 3).answers { (params, mock) =>
      params match {
        case Array(a, b: Int, c) => b + 2
      }
    }
    mockedService.invoke(1, 2, 3) must_== 4
  }
}

trait Service {
  def invoke(arg1: Int, arg2: Int, arg3: Int) = 1
}