简体   繁体   English

如何使用Mockk库模拟android上下文

[英]How to mock android context using mockk library

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. 我是在Android上进行JUnit测试的新手,并且正在测试一个函数,该函数使用android上下文对象获取字符串资源并进行一些比较。 How can I mock android context object to successfully test this function? 如何模拟android上下文对象以成功测试此功能? For testing I'm using Mockk testing library. 为了进行测试,我使用了Mockk测试库。

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

I was trying to mock context using mockk<Context>() , but I'm getting the following exception 我试图使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM