简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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