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)
}
和
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
}
任何建议都会有所帮助。谢谢!
最佳答案
目前,我在Android类上测试扩展功能的方式是通过模拟Android类。我知道,这不是一个最佳的解决方案,因为它模拟了被测类,并且需要有关该函数如何工作的某些知识(因为在模拟时通常是这种情况),但是由于扩展函数在内部实现为静态函数,我想这是可以接受的直到有人提出更好的建议。
作为示例,请考虑JsonArray
类。我们定义了一个扩展函数,用于接收最后一项的索引:
fun JSONArray.lastIndex() = length() - 1
相应的测试(使用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
}
}
}
})
函数的困难在于,它们还在内部使用Android类。不幸的是我现在没有解决方案。