android - 在 Android SDK 类上对 Kotlin 扩展功能进行单元测试

标签 android unit-testing kotlin kotlin-android-extensions kotlin-extension

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

关于android - 在 Android SDK 类上对 Kotlin 扩展功能进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38820556/

相关文章:

android - 如何从 Cursor 获取数据到 ContextMenu

silverlight - 使用MVVM/CSLA在Silverlight中进行XAML单元测试

java - 计数事件并测试 rxJava

php - 使用 vfsStream 测试 move_uploaded_file 和 is_uploaded_file

android - 如何在 Jetpack Compose 中使用参数进行导航?

java - 单击 editText 后,转到另一个 edittext 时完成

Java String 类 replaceAll 方法丢失

kotlin - 超时测试未返回TimeoutException-rxjava

Android Studio XML 需要 Layout_Height 和 Layout_Width

java - 如何在 Android Studio 中从 java 类意向到 kotlin 类