ant*_*009 5 android unit-testing android-webview kotlin
Android Studio 3.5.1
Kotlin 1.3
Run Code Online (Sandbox Code Playgroud)
我有以下尝试进行单元测试的方法。使用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 ?: ""))
}
}
}
Run Code Online (Sandbox Code Playgroud)
我采用了一个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()
}
Run Code Online (Sandbox Code Playgroud)
在单元测试中,我做了这样的事情:
@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)
}
Run Code Online (Sandbox Code Playgroud)
由于此单元测试的性质是异步的webView.webViewClient.onPageStarted
,因此您应该使用异步测试方法,而不是自己同步调用。通过这种方式,我们将URL传递WebView
给显示,然后等待该onPageStarted
方法WebView
本身被调用。
似乎在Android中运行异步单元测试的最佳选择是使用Awaitility。
build.gradle
dependencies {
testImplementation 'org.awaitility:awaitility:4.0.1'
}
Run Code Online (Sandbox Code Playgroud)
单元测试班
@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)
}
Run Code Online (Sandbox Code Playgroud)