17

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
}

任何建议都会有所帮助。谢谢!

4

1 回答 1

3

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

于 2017-03-02T14:53:32.677 回答