BakaOne
BakaOne

Reputation: 126

How to mock android.util.Patterns with Mockito or MockK

I have a method that I need to test :

fun validate(email: String): Result {
    return if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        Result(true)
    } else {
        Result(false, "error")
    }
}

But it returns a NullPointerException error because Patterns.email needs to be mocked. Right now I manually create and test the Pattern but cannot test the method above.

object Patterns {
    private const val EMAIL_PATTERN = ("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + 
        "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")

    val EMAIL_ADDRESS: Pattern = Pattern.compile(EMAIL_PATTERN)
}

Any idea how to do this with Mockito or MockK so I can test this method as a whole instead of creating the patterns manually in the test.

Upvotes: 2

Views: 1164

Answers (1)

LeoColman
LeoColman

Reputation: 7143

I believe you could use objectMockk, from Mockk:

objectMockk(Patterns.EMAIL_ADDRESS).use {
    every { Patterns.EMAIL_ADDRESS.matcher(email).matches() } returns true
    //Code that uses the mock here
}

You're going to mock the constant field Patterns.EMAIL_ADDRESS and then mock what you want it to return on the method matcher(email).matches().

I believe this is enough for your use case, but I'm not sure on how this lib is handled in Android.

Upvotes: 1

Related Questions