androidkotlinunit-testingjwtmocking

Mocking functions with every fails in Android unit tests on JWT


I have the following data class with its functions:

@JsonClass(generateAdapter = true)
data class AuthToken(
    @Json(name = "token") val access: String,
    @Json(name = "refreshToken") val refresh: String
) {
    fun isAccessTokenValid(): Boolean = isTokenValid(access)

    fun isRefreshTokenValid(): Boolean = isTokenValid(refresh)

    private fun isTokenValid(token: String): Boolean {
        return try {
            val jwt = JWT(token)
            val isExpired = jwt.isExpired(0)
            Timber.d("Token ${if (isExpired) "expired" else "valid"} [${jwt.details()}]")
            !isExpired
        } catch (e: DecodeException) {
            Timber.w(e, "Invalid auth token.")
            false
        }
    }
}

In my unit tests I have the following lines:

val authToken = AuthToken("accessToken", "refreshToken")
every { authToken.isAccessTokenValid() } returns true
every { authToken.isRefreshTokenValid() } returns false

But I get the following error:

Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock.

On line val jwt = JWT(token)

Why does the isTokenValid runs at all when I'm trying to mock the outer functions calling it?

Any idea how to solve it?


Solution

  • To stub object's methods you have to create it as a mockk:

    val authToken = mockk<AuthToken>()