[FIXED] Android mokito When(), thenReturn() is not working

Issue

I am writing test code using Android Mockito framework. I wrote the code to mock SharedPreference in the class to be tested. For this, SharedPreference was stubed using When() thenReturn(). As a result of debugging, null is continuously returned and the app dies with NullPointerException. Here is my code :

Test Code :

@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {

    @Mock
    public Context context;

    @Mock
    public SharedPreferences sharedPref;

    @Mock
    public SharedPreferences.Editor editor;

    TestA mTestA;
    String tempStringData = "";

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPref);
        when(sharedPref.edit()).thenReturn(editor);
        when(sharedPref.getString(anyString(), anyString())).thenReturn(tempStringData);

        mTestA = new TestA(context);
    }
}

TestA.class :

public class TestA {
    
    SharedPreference mSharedPref;

    public TestA(Context context) {
        mSharedPref = context.getSharedPreferences(context.getString(R.string.shrf_file_key), Context.MODE_PRIVATE);
        // return 'null'
    }
}

I think I did the stub correctly, but why does it keep returning null?

Solution

anyString() does not allow null objects.

context.getString(R.string.shrf_file_key) returns null.

If you want to allow null values as well, you can use nullable(String.class)

Answered By – vakio

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published