简体   繁体   English

mockk,如何为 MutableMap 使用插槽<String, String>

[英]mockk, how to use slot for MutableMap<String, String>

using mockk 1.9.3使用模拟 1.9.3

having a function to be verified有待验证的功能

class EventLogger private constructor()类 EventLogger 私有构造函数()

fun logUserEvent(eventName: String?, eventParamMap: MutableMap<String, String>?) {
   ......
    internaLogEventImpl(eventName, eventParamMap)
}

internal fun internaLogEventImpl(eventName: String?, customParams: MutableMap<String, String>?) { ...... }内部乐趣 internaLogEventImpl(eventName: String?, customParams: MutableMap<String, String>?) { ...... }

companion object {
     @Volatile
     private var sEventLoggerSingleton: EventLogger? = null

     @JvmStatic
    val instance: EventLogger
        get() {
            if (sEventLoggerSingleton == null) {
                sEventLoggerSingleton = EventLogger()
            }
            return sEventLoggerSingleton!!
        }
}

got compiler error at every {eventLogger.internaLogEventImpl(any(), mapSlot)}在每个 {eventLogger.internaLogEventImpl(any(), mapSlot)} 都有编译器错误在此处输入图片说明

Type mismatch.类型不匹配。 Required: MutableMap<String, String>?必需:MutableMap<String, String>? Found: CapturingSlot<MutableMap<String, String>> when trying this below :发现:CapturingSlot<MutableMap<String, String>> 在下面尝试时:

class TestK {类 TestK {

lateinit var eventLogger: EventLogger
lateinit var application: Application

val mapSlot = slot<MutableMap<String, String>>()

@Before
fun setUp() {
    application = ApplicationProvider.getApplicationContext<Application>()
    eventLogger = mockk.spyk(EventLogger.instance)
    ReflectionHelpers.setStaticField(EventLogger::class.java, "sEventLoggerSingleton", eventLogger)
}

@After
fun cleanUp() {
    ReflectionHelpers.setStaticField(EventLogger::class.java, "sEventLoggerSingleton", null)
}

@Test
fun logNotificationStatusChange_with_enabled_WhenCalled_ShouldLog() {

    val testMap = hashMapOf("action" to "open")

    every {eventLogger.internaLogEventImpl(any(), mapSlot)} answers {
        println(mapSlot.captured)
        assert(mapSlot.captured["action"] == "open")
    }
    eventLogger.logUserEvent("test_event", testMap)
}

} }

You need to use capture (see Mockk's Capturing section ).您需要使用capture (请参阅Mockk 的捕获部分)。

So for your case capture(mapSlot) should work.所以对于你的情况capture(mapSlot)应该有效。

eventLogger.internaLogEventImpl(any(), capture(mapSlot))

Before trying to mock on complex code, It would be better to learn on easier example.在尝试模拟复杂的代码之前,最好先学习更简单的示例。

Here is a working example to mock a private call on an object with mockk.这是一个使用 mockk 模拟object上的私有调用的工作示例。

object MyLogger {
    fun logUserEvent(event: String?, map: MutableMap<String, String>?) {
        // turns the event string into an uppercase string.
        internaLogEventImpl(event?.toUpperCase(), map)
    }

    private fun internaLogEventImpl(event: String?, map: MutableMap<String, String>?): Unit =
        throw Exception("real implementation")
}

How to test and mock the internal function so we don't throw the exception.如何测试和模拟内部函数,这样我们就不会抛出异常。

@Test
fun `test logger internal`() {
    val expectedMap = mutableMapOf("a" to "b")
    val expectedEvent = "EVENT"

    val mock = spyk(MyLogger, recordPrivateCalls = true)
    justRun { mock["internaLogEventImpl"](expectedEvent, expectedMap) }
    // or justRun { mock["internaLogEventImpl"](any<String>(), any<MutableMap<String, String>>()) }

    mock.logUserEvent("event", expectedMap)

    verify { mock["internaLogEventImpl"](expectedEvent, expectedMap) }
}

Here logUserEvent calls the real implementation and internaLogEventImpl calls the mock implementation.这里logUserEvent调用真正的实现, internaLogEventImpl调用模拟实现。

if justRun { mock["internaLogEventImpl"](expectedEvent, expectedMap) } is not called (or wrong because the argument doesn't match), the real implementation will be call.如果justRun { mock["internaLogEventImpl"](expectedEvent, expectedMap) }没有被调用(或者因为参数不匹配而错误),真正的实现将被调用。 Here it will throw Exception("real implementation") .在这里它会抛出Exception("real implementation")

Please try and modify values to check different behaviors.请尝试修改值以检查不同的行为。

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

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