9

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?

Thomas Cirksena
  • 717
  • 2
  • 8
  • 28
  • Have a look at [Robolectric](http://robolectric.org/). This should do it – StuStirling Jul 05 '19 at 09:15
  • I don't use Robolectric for now so that's not a option, sorry – Thomas Cirksena Jul 05 '19 at 09:17
  • You can't use Android components in Java unit tests. So something like that is your only option. – StuStirling Jul 05 '19 at 09:18
  • You can return `CharSequence` instead of `SpannableString` and then use the methods in unit tests. It's not clear what you are trying to test from the code in your question though. If you could clarify then maybe we could help more – Jahnold Jul 05 '19 at 09:23

0 Answers0