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 ?: ""))
}
}
}
我使用一个WebView,该WebView覆盖了WebViewClient的某些回调。然后在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)
}
答案 0 :(得分:5)
由于此单元测试的性质是异步的,因此您应该使用异步测试方法,而不是自己自己同步调用webView.webViewClient.onPageStarted
。这样,我们将URL传递给WebView
进行显示,然后等待onPageStarted
本身调用WebView
方法。
似乎在Android中运行异步单元测试的最佳选择是使用Awaitility。
build.gradle
dependencies {
testImplementation 'org.awaitility:awaitility:4.0.1'
}
单元测试课程
@Test
fun `should set the correct settings of the WebView`() {
val requestedUrl = "https://www.google.com"
var resultUrl: String? = null
// Arrange the webView
val webView = WebView(RuntimeEnvironment.application.baseContext)
// Act by calling the setPageStatus
webFragment.setPageStatus(webView) { pageStatusResult ->
when (pageStatusResult) {
is PageStatusResult.PageStarted -> {
resultUrl = pageStatusResult.url
}
}
}
// trying to load the "requestedUrl"
webView.loadUrl(requestedUrl)
// waiting until the "onPageStarted" is called
await().until { resultUrl != null }
// now check the equality of URLs
assertThat(resultUrl).isEqualToIgnoringCase(requestedUrl)
}