1

我正在编写一个模拟对象,如下所示:

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...

这种情况下正确的参数匹配器是什么?非常感谢。

4

1 回答 1

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)
于 2013-09-26T23:30:42.607 回答