SparseIntArray doesn’t change when being tested with Robolectric

Issue

I’m new to Robolectric and I’m trying to unit test a simple getter/setter code, but it seems that the SparseIntArray isn’t working as expected when testing with Robolectric and it simply doesn’t change. (i always get ‘0’ with the get method).

I also tried adding a static getter for the SparseIntArray itself and found out that after calling the setter, the array size is 0.

what am I missing here ?

this is the code I’m trying to test:

public class MyClass {
    private static SparseIntArray sRequestStatus;

public static int getStatus(int request) {
    return sRequestStatus.get(request);
}

public static void setStatus(int request, int status) {
    if (sRequestStatus.get(request) ! 0) {
        sRequestStatus.delete(request);
        sRequestStatus.put(request, status);
    } else {
        sRequestStatus.put(request, status);
    }
}

    static {
    sRequestStatus  new SparseIntArray();
    }
}

and this is the test:

@RunWith(RobolectricTestRunner.class)
public class MyClassTests {

@Test
public void testGetSetStatus() throws Exception {
    // get status should return 0 for non-exisiting request
    assertEquals(0, MyClass.getStatus(1));

    // set status should add a request mapping
    MyClass.setStatus(1, 1);
    assertEquals(1, MyClass.getStatus(1));

    // set status should change the request status if mapping exists
    MyClass.setStatus(1, 2);
    assertEquals(2, MyClass.getStatus(1));
}

Solution

turns out there wasn’t a Shadow for SparseIntArray in the version of Robolectric I was using..

Answered By – Gal Ben-Haim

Leave a Comment