You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中使用mockK模拟Instant.now()?

解决mockK模拟Instant.now()的报错问题

你遇到的错误Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock,是因为mockK未正确识别到Instant.now()的静态mock配置,可通过以下方式解决:

方法一:精确mock目标静态方法

直接指定要mock的Instant.now()方法,而非整个类,确保mockK精准覆盖目标方法:

@Test
fun testStaticMock() {
    val instant = Instant.parse("2024-03-22T12:00:00.000Z")
    mockkStatic(Instant::now) {
        every { Instant.now() } returns instant
        val actual = Instant.now()
        assertEquals(instant, actual)
    }
}

方法二:使用Java类引用mock

对于Java原生类,传入Instant::class.java替代Kotlin的Instant::class,避免类型识别问题:

@Test
fun testStaticMock() {
    val instant = Instant.parse("2024-03-22T12:00:00.000Z")
    mockkStatic(Instant::class.java) {
        every { Instant.now() } returns instant
        val actual = Instant.now()
        assertEquals(instant, actual)
    }
}

更推荐的方案:避免静态方法mock(使用Clock依赖)

静态方法mock容易引入测试上下文污染,更优雅的方式是通过Clock类控制时间,业务代码依赖Clock对象而非直接调用Instant.now():

// 业务代码示例
fun getCurrentTime(clock: Clock = Clock.systemUTC()): Instant {
    return Instant.now(clock)
}

// 测试代码
@Test
fun testWithClock() {
    val fixedInstant = Instant.parse("2024-03-22T12:00:00.000Z")
    val fixedClock = Clock.fixed(fixedInstant, ZoneOffset.UTC)
    
    val actual = getCurrentTime(fixedClock)
    assertEquals(fixedInstant, actual)
}

内容的提问来源于stack exchange,提问作者nagy.zsolt.hun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:48:11