Ely*_*lye 16 android unit-testing kotlin kotlin-extension kotlin-android-extensions
Kotlin扩展功能很棒.但是我怎么能对它们进行单元测试呢?特别是那些Android SDK提供的类(例如Context,Dialog).
我在下面提供了两个例子,如果有人可以分享我如何对它们进行单元测试,或者如果我真的想对它们进行单元测试,我是否需要以不同方式编写它们.
fun Context.getColorById(colorId: Int): Int {
if (Build.VERSION.SDK_INT >= 23)
return ContextCompat.getColor(this, colorId)
else return resources.getColor(colorId)
}
Run Code Online (Sandbox Code Playgroud)
和
fun Dialog.setupErrorDialog(body : String, onOkFunc: () -> Unit = {}): Dialog {
window.requestFeature(Window.FEATURE_NO_TITLE)
this.setContentView(R.layout.dialog_error_layout)
(findViewById(R.id.txt_body) as TextView).text = body
(findViewById(R.id.txt_header) as TextView).text = context.getString(R.string.dialog_title_error)
(findViewById(R.id.txt_okay)).setOnClickListener{
onOkFunc()
dismiss()
}
return this
}
Run Code Online (Sandbox Code Playgroud)
任何建议都会有所帮助.谢谢!
我目前在 Android 类上测试扩展函数的方法是通过模拟 Android 类。我知道,这不是一个最佳解决方案,因为它模拟了被测试的类,并且需要有关该函数如何工作的一定知识(因为模拟时总是如此),但由于扩展函数在内部实现为静态函数,我想这是可以接受的直到有人想出更好的东西。
作为一个例子,考虑一下JsonArray班级。我们定义了一个扩展函数来接收最后一项的索引:
fun JSONArray.lastIndex() = length() - 1
Run Code Online (Sandbox Code Playgroud)
相应的测试(使用Spek测试框架和mockito-kotlin)如下所示。
@RunWith(JUnitPlatform::class)
object JsonExtensionTestSpec : Spek({
given("a JSON array with three entries") {
val jsonArray = mock<JSONArray> {
on { length() } doReturn 3
}
on("getting the index of the last item") {
val lastIndex = jsonArray.lastIndex()
it("should be 2") {
lastIndex shouldBe 2
}
}
}
given("a JSON array with no entries") {
val jsonArray = mock<JSONArray>({
on { length() } doReturn 0
})
on("getting the index of the last item") {
val lastIndex = jsonArray.lastIndex()
it("should be -1") {
lastIndex shouldBe -1
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
您的函数的困难在于,它们还在内部使用 Android 类。不幸的是我现在没有解决方案。
| 归档时间: |
|
| 查看次数: |
800 次 |
| 最近记录: |