我目前正在使用Kotest和MockK在Kotlin编写测试. 在使用kotest和MockK用Kotlin编写测试时,我在模拟过程中遇到了一个错误.

every { accountService.findAccount(nonExistAccountId.toString()) } just Runs
//Kotlin: Type mismatch: inferred type is Runs but Awaits was expected

但之前,我在同样的过程中没有遇到任何问题.

every { noticeRepository.delete(any()) } just  Runs
//no error

所以,我判断了"公正"的声明.

/**
 * Part of DSL. Answer placeholder for Unit returning functions.
 */
@Suppress("UNUSED_PARAMETER")
infix fun MockKStubScope<Unit, Unit>.just(runs: Runs) = answers(ConstantAnswer(Unit))

/**
 * Part of DSL. Answer placeholder for never returning suspend functions.
 */
@Suppress("UNUSED_PARAMETER")
infix fun <T, B> MockKStubScope<T, B>.just(awaits: Awaits) = coAnswers { awaitCancellation() }

为什么上面的函数没有被调用?

推荐答案

因此,在本例中没有错误,因为noticeRepository中的delete()方法返回Unit.

every { noticeRepository.delete(any()) } just  Runs

just Runs仅用于模拟返回Unit的函数或方法的响应

当您想模拟实际返回值的方法的响应时,您可以使用不同的方法

every { accountService.findAccount(nonExistAccountId.toString()) } returns // add your Account mock value here

更多细节可以在这里找到:https://mockk.io/#answers

Kotlin相关问答推荐

如何访问方法引用的接收者?

将文本与文本字段的内容对齐

Kotlin 函数名后面的大括号是什么意思?

如何使用multiset与JOOQ获取关联的记录列表?

为什么我的通用Kotlin函数中的这个转换未经判断?

如何从 Period.between() 返回的字符串中提取信息? (Kotlin )

Kotlin 数据类中的大量参数

Kotlin SAM/功能接口抛出 AbstractMethodError

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

Kotlin 具体类从抽象类和接口扩展而来,接口使用抽象类中实现的方法

Kotlin 中列表或数组的乘积

在 APK META-INF/library_release.kotlin_module 中复制的重复文件

为什么 Kotlin 需要函数引用语法?

在 Spring Framework 5.1 中注册具有相同名称的测试 bean

Jacoco在Gradle 7.0.2和Kotlin 1.5.10上失败

如何在Kotlin中创建无限长的序列

接口中的属性不能有支持字段

如何启用spring security kotlin DSL?

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

将字符串编码为Kotlin中的UTF-8