0

I have the following simple ArrayAdapter that I'd like to run UnitTests on:

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
    }
}

getCount, getItem and getItemId is easily done.

But how can I test the getView and getDropDownView methods? Problems that I am facing are:

  • the 3rd parameter viewGroup can not be null. How to fake/mock this ViewGroup?
  • both methods are calling super.xxx. How can I set up a when/then construct to let it return a TextView?
Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
muetzenflo
  • 5,653
  • 4
  • 41
  • 82

2 Answers2

0

Simply you can't test any android dependency on JVM, because you don't have context to be able to get views or anything related to it, to test getView() and getDropDownView() you have 2 options

  1. Write Instrumentation test using espresso or equivalent (https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests)
  2. Write your tests to run on JVM using Android shadows by using Robolectric, http://robolectric.org
Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Eslam Ahmad
  • 579
  • 7
  • 7
0

For unit tests the whole view should be mocked with view = mock() on @Before the test.

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

see: Android Unit Testing with Mockito.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216