I am new in JUnit testing on Android and I'm testing a function, which is using android context object to get a string resources and making some comparsions. How can I mock android context object to successfully test this function? For testing I'm using Mockk testing library.

  private val context = mockk<Context>()
  private val contextWrapper = ApplicationContextWrapper(context)
  private val objectUnderTest = AppLinkService(contextWrapper)

我试图用mockk<Context>()模拟上下文,但我得到了以下例外

io.mockk.MockKException: no answer found for: Context(#1).getApplicationContext()

推荐答案

Ok, I found the answer. Using relaxed mock solved my problem

val mContextMock = mockk<Context>(relaxed = true)

Kotlin相关问答推荐

测试Compose Multiplatform UI时,为另一个文件设置ComposeRule()

在Kotlin中可以连接两个范围吗?

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

如何在 Spring Boot 3 中为内部类提供运行时提示

为什么多线程不会使执行更快

如何在 Android 的 Fragment 中使用 setUserVisibleHint

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

Kotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定

Kotlin - mutableMapOf() 会保留我输入的顺序

使用 Paging 3 时保存并保留 LazyColumn 滚动位置

在调用Kotlin数据类中的超类构造函数之前访问函数

Tornadofx - 如何在每个实例上将参数传递给 Fragment

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

如何将 CameraView 与 Jetpack Compose 一起使用?

内联 Kotlin 方法没有覆盖报告

Kotlin中的嵌套let块

Java的Kotlin:字段是否可以为空?

如何在 spring-boot Web 客户端中发送请求正文?