如何在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
相关产品推荐
相关产品推荐

