vendredi 5 juillet 2019

How to use SpannableString in Android UnitTests

I just stumbled across a problem again where I haven't found a solution yet, so I thought I'd ask you :)

Suppose I have the following method (Kotlin):

fun getValue(): SpannableString {

    val value = "MyTestValue"
    val subString = "Test"

    // init spannable string
    val spannableString = SpannableString(value)

    // get position of substring
    val position = value.indexOf(subString)

    // insert span
    spannableString.setSpan(BackgroundColorSpan(ContextCompat.getColor(context, R.color.yellow)), position, position + subString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

    // return result
    return spannableString
}

And this is my Unit-Test method:

@Test
fun `value | on filter | returns correct value`() {

    // define mock behavior
    val model = TestUtils.getTestModel() //returns a test model

    // init Observable
    val observable = TestObservable(model)

    // check assertions
    assertEquals("???", observable.getValue()) // I don't know what to expect here
}

If I now want to check this method in the unit test I always get 'null' as response because SpannableString returns this value. I am aware that I could run the test in the androidTest context, but there unit tests have nothing to do (in my opinion).

I think there should be some way to test this without running an emulator.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire