Kotlin:ArrayAdapter的单元测试getView方法

问题描述 投票:0回答:2

我有以下简单的ArrayAdapter,我想在其上运行UnitTests:

class AccountSpinnerAdapter(context: Context, textViewResourceId: Int, private val values: Set<Account>) : ArrayAdapter<Account>(context, textViewResourceId, values.toList()) {

    override fun getCount() = values.size
    override fun getItem(position: Int) = values.elementAt(position)
    override fun getItemId(position: Int) = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val label = super.getView(position, convertView, parent) as TextView
        label.text = values.elementAt(position).displayName
        return label
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        val label = super.getDropDownView(position, convertView, parent) as TextView
        label.text = values.elementAt(position).displayName
        return label
    }
}

[getCountgetItemgetItemId容易完成。

但是如何测试getViewgetDropDownView方法?我面临的问题是:

  • 第三个参数viewGroup不能为null。如何伪造/模拟此ViewGroup?
  • 两个方法都调用super.xxx。如何设置when/then构造以使其返回TextView
android unit-testing mockito android-testing mockito-kotlin
2个回答
0
投票
简单地说,您无法测试对JVM的任何Android依赖,因为您没有上下文来获取视图或与之相关的任何东西,因此要测试getView和getDropDownView,您有2个选项

    使用浓缩咖啡或同等水平的书写工具测试[https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests] >>
  1. 使用Robolectric,http://robolectric.org将测试写成使用Android阴影在JVM上运行的程序>
  • 对于单元测试,应在测试的view = mock()上使用@Before来模拟整个视图。

    // https://mvnrepository.com/artifact/com.nhaarman/mockito-kotlin testImplementation 'com.nhaarman:mockito-kotlin:1.6.0'

    请参阅:Android Unit Testing with Mockito

  • 0
    投票
    对于单元测试,应在测试的view = mock()上使用@Before来模拟整个视图。
    © www.soinside.com 2019 - 2024. All rights reserved.