Android SDK类上的Kotlin扩展函数的单元测试

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类。 不幸的是,我现在还没有解决方案。