简体   繁体   English

如何使用 Mockito 或 MockK 模拟 android.util.Patterns

[英]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.但它返回一个NullPointerException错误,因为Patterns.email需要被模拟。 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.任何想法如何使用MockitoMockK执行此操作,以便我可以整体测试此方法,而不是在测试中手动创建模式。

I believe you could use objectMockk , from Mockk:我相信你可以使用objectMockk ,从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() .您将模拟常量字段Patterns.EMAIL_ADDRESS ,然后模拟您希望它在方法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.我相信这对于您的用例来说已经足够了,但我不确定这个库在 Android 中是如何处理的。

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

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