【问题标题】:Scala Spec2 Mockito: matchers for non-primitive arguments: any, isAScala Specs2 Mockito:非原始参数的匹配器:any,isA
【发布时间】:2013-09-27 16:36:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: scala arguments mockito matcher specs2


    【解决方案1】:

    您需要使用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)
    

    【讨论】:

    • 非常感谢上面详尽的回答。现在,我需要传递一个复杂的参数 Map[String,Seq[String]],而不是 MonetaryValue 类型。如何定义匹配器?非常感谢,埃里克。
    • any[Map[String,Seq[String]]] 不起作用。我试图通过 ArgumentMatcher 定义一个新的匹配器(并使用了 argThat),但又遇到了另一个错误。
    • 对我来说一切正常。您能否打开另一个问题,显示您的确切尝试和相应的错误消息?
    • 我已经在这件事上苦苦挣扎了 30 分钟(这比听起来要长)。谢谢。
    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多