使用mockk模拟ZonedDateTime.now()以“io.mockk.MockKException:每个{...}块内缺少模拟调用”结束

问题描述 投票:0回答:1

我正在尝试为这段代码编写一些测试:

private companion object {
    val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z")
}

fun getSomeValue(): String {
    val dateTime = ZonedDateTime.parse(config.getSomeDateTime(), formatter)
    return if (dateTime < ZonedDateTime.now()) {
        "A"
    } else {
        "B"
    }
}

这是不起作用的测试:

@Test
fun testGetSomeValue() {
    mockkStatic(ZonedDateTime::class) {
        val mockZDT: ZonedDateTime = ZonedDateTime.of(2023, 12, 1, 12, 34, 56, 0, ZoneId.of("UTC"))
        every { ZonedDateTime.now() } returns mockZDT --> exception
        every { config.getSomeDateTime() } returns "2023-05-01 01:23:45 UTC"
        service.getSomeValue() shouldBe "A"
    }
}

测试的输出是:

io.mockk.MockKException: Missing mocked calls inside every { ... } block: make sure the object inside the block is mock

我一直在通过互联网寻找解决方案,有些地方说它应该有效(即OffsetDateTime问题

另一方面,当我将 Mockito 解决方案与mockito-inline 中的“mockStatic”一起使用时,我没有任何问题。但这是我继承的代码,需要进行小的更改请求,因此我不想添加额外的依赖项。

我正在使用:

  • 模拟1.13.5
kotlin junit5 mockk
1个回答
0
投票

以下示例代码是通过的完整、可重现的测试:

import io.kotest.matchers.shouldBe
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import org.junit.jupiter.api.Test
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

class MyTest {
    interface Config {
        fun getSomeDateTime(): String
    }

    class Service(private val config: Config) {
        private companion object {
            val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z")
        }

        fun getSomeValue(): String {
            val dateTime = ZonedDateTime.parse(config.getSomeDateTime(), formatter)
            return if (dateTime < ZonedDateTime.now()) {
                "A"
            } else {
                "B"
            }
        }
    }

    val config = mockk<Config>()

    val service = Service(config)

    @Test
    fun testGetSomeValue() {
        mockkStatic(ZonedDateTime::class) {
            val mockZDT: ZonedDateTime = ZonedDateTime.of(2023, 12, 1, 12, 34, 56, 0, ZoneId.of("UTC"))
            every { ZonedDateTime.now() } returns mockZDT
            every { config.getSomeDateTime() } returns "2023-05-01 01:23:45 UTC"
            service.getSomeValue() shouldBe "A"
        }
    }
}

版本:Mockk 1.13.8、Kotlin 1.9.21、JVM 目标 21。

要使其在最新的 JVM 上工作,您需要应用https://mockk.io/doc/md/jdk16-access-exceptions.html中详细介绍的解决方法。

© www.soinside.com 2019 - 2024. All rights reserved.