Dmytro
Dmytro

Reputation: 2319

Creating new SpannableStringBuilder returns null

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());
}


}

Upvotes: 3

Views: 2694

Answers (3)

pzulw
pzulw

Reputation: 1756

@RunWith(RobolectricTestRunner::class)

Using Robolectric resolves the issue.

Upvotes: 5

Dmytro
Dmytro

Reputation: 2319

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.

Upvotes: 10

OldCurmudgeon
OldCurmudgeon

Reputation: 65869

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.

Upvotes: 1

Related Questions