【发布时间】:2019-10-18 19:30:57
【问题描述】:
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)
}
【问题讨论】:
标签: android unit-testing kotlin android-webview