【发布时间】:2016-02-02 22:07:27
【问题描述】:
我试图在 mockito 中模拟 scala 的名称调用方法。但是遇到了这个错误。
如果匹配器与原始值组合,则可能会发生此异常: //不正确: someMethod(anyObject(), "原始字符串");使用匹配器时,所有参数都必须由匹配器提供。例如: //正确的: someMethod(anyObject(), eq("String by matcher"));
任何建议将不胜感激。谢谢!
这里是示例代码和测试文件:这里我试图模拟 createCommand 函数。并给出一个模拟,以便我可以验证 execute 是否被调用。
package com.example
class Command(key: String, func: => Long) {
def execute(): Long = {
println("Command.execute")
println("key = " + key)
println("func = " + func)
func
}
}
class CacheHelper {
def createCommand(cacheKey: String, func: => Long): Command = {
println("cacheKey = " + cacheKey)
println("func = " + func)
new Command(cacheKey, func)
// Mock this method
}
def getOrElse(cacheKey: String)(func: => Long): Long = {
println("circuitBreakerEnabled = " + isCircuitBreakerEnabled)
if (isCircuitBreakerEnabled) {
val createCommand1: Command = createCommand(cacheKey, func)
println("createCommand1 = " + createCommand1)
createCommand1.execute()
}
else {
util.Random.nextInt()
}
}
def isCircuitBreakerEnabled: Boolean = {
println("CacheHelper.isCircuitBreakerEnabled")
false
}
}
import com.example.{CacheHelper, Command}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatest.{Matchers, _}
import org.scalatest.mock.MockitoSugar
class ExampleSpec extends FlatSpec with Matchers with BeforeAndAfter with MockitoSugar {
"it" should "call commands execute" in {
val cacheHelper: CacheHelper = new CacheHelper
val commandMock: Command = mock[Command]
val spyCacheHelper = spy(cacheHelper)
when(spyCacheHelper.isCircuitBreakerEnabled).thenReturn(true)
when(spyCacheHelper.createCommand(any(), anyLong())).thenReturn(commandMock)
val result: Long = spyCacheHelper.getOrElse("key")(1L)
println("result = " + result)
verify(commandMock).execute()
}
}
【问题讨论】:
-
您需要包含更多错误堆栈跟踪信息,以便有人帮助您回答这个问题。
-
您已将值作为参数
anyLong()发送,但您必须从Unit => Long发送一些函数 -
我收到
Unit=>Long的错误,因为这是名称参数调用,而不是功能参数。 -
以下是依赖项,如果有人想尝试一下:
libraryDependencies += "org.mockito" % "mockito-all" % "1.10.19" % "test" libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.4" % "test"
标签: scala unit-testing mockito scala-java-interop