Taras Stavnychyi
Taras Stavnychyi

Reputation: 975

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. 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)

I was trying to mock context using mockk<Context>(), but I'm getting the following exception

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

Upvotes: 24

Views: 16533

Answers (2)

Fred B.
Fred B.

Reputation: 1721

In general, it would be risky to mock a context as it provides information about the application environment and does a lot under the hood.

ApplicationProvider provides the ability to retrieve the current application Context in tests. All you need to do is import the latest version of the androidx:test:core library

dependencies {
    // To use the androidx.test.core APIs
    androidTestImplementation("androidx.test:core:1.5.0")
    ...
}

And then retrieve the context in your test class

private val context = ApplicationProvider.getApplicationContext()

Upvotes: 1

Taras Stavnychyi
Taras Stavnychyi

Reputation: 975

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

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

Upvotes: 50

Related Questions