简体   繁体   English

使用Mockk匹配任何varargs

[英]Using mockk to match any varargs

I'm trying to mock an Android Context to return a string from a resource id. 我正在尝试模拟Android上下文,以从资源ID返回字符串。 However I have trouble matching the stub to the call, I assume it is because of the varargs. 但是,我很难将存根与调用匹配,我认为这是因为varargs。 However I am new to mockk so I might just miss something very easy. 但是,我是mock的新手,所以我可能会很容易错过一些事情。

I mock the context this way: 我这样模拟上下文:

val context = mockk<Context>()
every { context.getString(any(), any()) } returns stringToReturn

But when calling getString on the object it throws the following exception: 但是,当在对象上调用getString时,它将引发以下异常:

io.mockk.MockKException: no answer found for: Context(#1).getString(2131689544, [])

If it is important, I call the function in the class under test similar to this. 如果重要的话,我在被测类中调用与此类似的函数。 formatArgs may be empty but doesn't have to: formatArgs可以为空,但不必:

protected fun foo(stringResource: Int, vararg formatArgs: Any) {
    val s = context.getString(errorMessageStringResource, *formatArgs)

Any idea how I can fix this? 知道我该如何解决吗?

You can check the project and reproduce the exception here: Github Project 您可以在此处检查项目并重现异常: Github Project

There is a related open issue in mockk v1.9: https://github.com/mockk/mockk/issues/224 (see referenced issues as well) 嘲笑 v1.9中存在一个相关的未解决问题: https : //github.com/mockk/mockk/issues/224 (也请参见参考的问题)

I tried several solutions but I ended up creating overloaded functions just for testing with mockk , eg. 我尝试了几种解决方案,但最终创建了仅用于用ockock测试的重载函数。

class Context {
    // Renamed because of same JVM signature
    fun foo2(stringResource: Int, vararg formatArgs: Any) = foo(stringResource, formatArgs)

    // Function accepts 
    fun foo(stringResource: Int, formatArgs: args: Array<out Any>) = ...
}

then test the non-vararg foo() function with mockk . 然后使用mockk测试non-vararg foo()函数。

I know it's an ugly workaround but if you find a better one please let me know :) 我知道这是一个丑陋的解决方法,但是如果您找到更好的方法,请告诉我:)

Version 1.9.1 introduces few additional matchers to match varargs. 1.9.1版引入了一些额外的匹配器来匹配varargs。

https://mockk.io/#varargs https://mockk.io/#varargs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM