Creating new SpannableStringBuilder returns null

2.4k views Asked by At

Here is my unit test. Somehow when I create instantiate SpannableStringBuilder instance with a non-null string argument, it appears to be null. What's wrong with this code?

public class CardNumberTextWatcherTest {

private CardNumberTextWatcher watcher;

@Before
public void setUp() throws Exception {
    watcher = new CardNumberTextWatcher();
}


@Test
public void afterTextChanged_cardNumberDividedWithSpaces() {
    assertTransformText("1111222233334444", "1111 2222 3333 4444");
}

private void assertTransformText(final String testStr,
                                 final String expectedStr) {
    final CardNumberTextWatcher watcher = new CardNumberTextWatcher();
    final Editable actualStr = new SpannableStringBuilder(testStr);
    // When I debug I see that actualStr value is null. Therefore test 
    //doesn't pass. What's the problem?
    watcher.transformText(actualStr);
    assertEquals(expectedStr, actualStr.toString());
}


}
3

There are 3 answers

1
Dmytro On BEST ANSWER

The problem was in the testing directory. As soon as SpannableStringBuilder is a part of Android SDK, it couldn't be resolved in regular JUnit test directory. When I moved my class to androidTest directory, everything started to work as expected.

0
pzulw On
@RunWith(RobolectricTestRunner::class)

Using Robolectric resolves the issue.

0
OldCurmudgeon On

You are calling actualStr.toString() which is what the assertion is comparing with, not actualStr itself so look for routes through SpannableStringBuilder to see what could result in null from toString(). Probably testStr is null.