Scala Specs2 Mockito:非原始参数的匹配器:any,isA

时间:2013-09-26 15:17:16

标签: scala arguments mockito matcher specs2

我正在编写如下的模拟对象:

import org.specs2.mock._
import com...MonetaryValue
import com...Voucher
import org.mockito.internal.matchers._

/**
 * The fake voucher used as a mock object to test other components
 */
case class VoucherMock() extends Mockito {
  val voucher: Voucher = mock[Voucher]

  //stubbing
  voucher.aMethod(any(classOf[MonetaryValue])) answers {arg => //some value to be return based on arg} 

  def verify() = {
    //verify something here
  }
}

存根步骤抛出异常:

 ...type mismatch;
[error]  found   : Class[com...MonetaryValue](classOf[com...MonetaryValue])
[error]  required: scala.reflect.ClassTag[?]
[error]   voucher.aMethod(any(classOf[MonetaryValue])) answers {arg => //some value to be return based on arg} 

我想从参数中获取值并根据此参数返回一个值,如下所示:http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#11

我尝试了isA, anyObject...

此案例的正确参数匹配器是什么?非常感谢你。

1 个答案:

答案 0 :(得分:6)

您需要使用any[MonetaryValue]。这是一个完整的例子:

class TestSpec extends Specification with Mockito { def is = s2"""
  test ${
    val voucher: Voucher = mock[Voucher]

    // the asInstanceOf cast is ugly and 
    // I need to find ways to remove that
    voucher.aMethod(any[MonetaryValue]) answers { m => m.asInstanceOf[MonetaryValue].value + 1}
    voucher.aMethod(MonetaryValue(2)) === 3
  }
  """
}

trait Voucher {
  def aMethod(m: MonetaryValue) = m.value
}
case class MonetaryValue(value: Int = 1)