我试图在mockito 中模拟scala 按名称调用方法。但遇到这个错误。
如果匹配器与原始值组合,则可能会出现此异常:
//不正确:
someMethod(anyObject(), "原始字符串");使用匹配器时,所有参数都必须由匹配器提供。例如:
//正确的:
someMethod(anyObject(), eq("匹配器的字符串"));
任何建议将不胜感激。谢谢!
这是示例代码和测试文件:Here Im试图模拟创建命令功能。并进行模拟,以便我可以验证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()
}
}
无法使用 Mockito 做到这一点:在 Mockito 中验证名称参数 https://stackoverflow.com/questions/24323213/verifying-by-name-parameters-in-mockito
应该能够用 scalamock 做到这一点:如何使用 ScalaMock 模拟按名称调用参数(如 getOrElse)? https://stackoverflow.com/questions/18294830/how-to-mock-a-call-by-name-argument-like-getorelse-using-scalamock
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)