Android Studio 3.5.1
Kotlin 1.3
我有一个需要进行单元测试的方法,它使用了WebView
和WebViewClient
我要测试的方法如下:
fun setPageStatus(webView: WebView?, pageStatus: (PageStatusResult) -> Unit) {
webView?.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
pageStatus(PageStatusResult.PageStarted(url ?: "", favicon))
}
override fun onPageFinished(view: WebView?, url: String?) {
pageStatus(PageStatusResult.PageFinished(url ?: ""))
}
}
}
我使用一个重写了WebViewClient的webView,并在onPageStarted或onPageFinished中调用一个lambda函数。
使用密封类来设置传递给lambda方法的属性。
sealed class PageStatusResult {
data class PageFinished(val url: String) : PageStatusResult()
data class PageStarted(val url: String, val favicon: Bitmap?) : PageStatusResult()
}
在单元测试中,我做了如下操作:
@Test
fun `should set the correct settings of the WebView`() {
// Arrange the webView
val webView = WebView(RuntimeEnvironment.application.baseContext)
// Act by calling the setPageStatus
webFragment.setPageStatus(webView) { pageStatusResult ->
when(pageStatusResult) {
is PageStarted -> {
// Assert that the url is correct
assertThat(pageStatusResult.url).isEqualToIgnoringCase("http://google.com")
}
}
}
// Call the onPageStarted on the webViewClient and and assert in the when statement
webView.webViewClient.onPageStarted(webView, "http://google.com", null)
}
https
,因为在没有网络安全配置的情况下,http
可能会失败。 - Martin Zeitler