在specs2中使用重载方法有什么技巧吗?

时间:2015-09-25 14:14:01

标签: scala mockito specs2

我一直在努力尝试匹配重载方法。

我是scala和specs2的新手,所以这可能是一个因素;)

所以我嘲笑了这个SchedulerDriver class

我正在尝试验证正在存在的参数的内容 传递给了这个launchTasks方法的签名:

http://mesos.apache.org/api/latest/java/org/apache/mesos/SchedulerDriver.html#launchTasks(java.util.Collection,%20java.util.Collection)

我尝试了answers这样的风格:

val mockSchedulerDriver = mock[SchedulerDriver]
mockSchedulerDriver.launchTasks(haveInterface[Collection[OfferID]], haveInterface[Collection[TaskInfo]]) answers { i => System.out.println(s"i=$i") }

并获取

ambiguous reference to overloaded definition, both method launchTasks in trait SchedulerDriver of type (x$1: org.apache.mesos.Protos.OfferID, x$2: java.util.Collection[org.apache.mesos.Protos.TaskInfo])org.apache.mesos.Protos.Status and method launchTasks in trait SchedulerDriver of type (x$1: java.util.Collection[org.apache.mesos.Protos.OfferID], x$2: java.util.Collection[org.apache.mesos.Protos.TaskInfo])org.apache.mesos.Protos.Status match argument types (org.specs2.matcher.Matcher[Any],org.specs2.matcher.Matcher[Any])

我尝试了capture这样的风格:

val mockSchedulerDriver = mock[SchedulerDriver]
val offerIdCollectionCaptor = capture[Collection[OfferID]]
val taskInfoCollectionCaptor = capture[Collection[TaskInfo]]
there was one(mockSchedulerDriver).launchTasks(offerIdCollectionCaptor, taskInfoCollectionCaptor)

并获得:

overloaded method value launchTasks with alternatives: (x$1: org.apache.mesos.Protos.OfferID,x$2: java.util.Collection[org.apache.mesos.Protos.TaskInfo])org.apache.mesos.Protos.Status <and> (x$1: java.util.Collection[org.apache.mesos.Protos.OfferID],x$2: java.util.Collection[org.apache.mesos.Protos.TaskInfo])org.apache.mesos.Protos.Status cannot be applied to (org.specs2.mock.mockito.ArgumentCapture[java.util.Collection[mesosphere.mesos.protos.OfferID]], org.specs2.mock.mockito.ArgumentCapture[java.util.Collection[org.apache.mesos.Protos.TaskInfo]])

任何关于如何接受这一点的指导或建议......!

最好的, 贝。

2 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用any匹配器:

val mockSchedulerDriver = mock[SchedulerDriver]

mockSchedulerDriver.launchTasks(
 any[Collection[OfferID]],     
 any[Collection[TaskInfo]]) answers { i => System.out.println(s"i=$i")

不同之处在于any[T]Matcher[T],并且在这种情况下重载解决方案有效(而haveInterfaceMatcher[AnyRef]所以它无法指导重载决议)。

答案 1 :(得分:0)

我不明白为什么第一个替代方案不起作用,但第二个替代方案不起作用,因为scala在解析哪个重载方法时不考虑隐式函数,并且允许你使用capture的魔法就像你捕获的东西一样取决于隐式函数调用。

那么如果你明确指出怎么办?

val mockSchedulerDriver = mock[SchedulerDriver]
val offerIdCollectionCaptor = capture[Collection[OfferID]]
val taskInfoCollectionCaptor = capture[Collection[TaskInfo]]
there was one(mockSchedulerDriver).launchTasks(
    offerIdCollectionCaptor.capture, taskInfoCollectionCaptor.capture)