【问题标题】:Unit test on Kotlin Extension Function on Android SDK Classes在 Android SDK 类上对 Kotlin 扩展功能进行单元测试
【发布时间】:2016-12-13 17:14:03
【问题描述】:

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 资源中获取颜色,而不是依赖于您的应用程序代码。第二个显示errorDialog,你为什么不用Espresso或者Robotium或者其他UI测试框架来检查它是否正确显示?
  • 感谢 piotrek。该代码仅作为示例。该问题的主要要点是探索如何在扩展功能上进行单元测试,以防万一需要测试其中的某些逻辑。这是无法实现的,还是我错过了什么?谢谢。
  • 我也在找它。 @Elye 你找到了吗?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多