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


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 :

public class ExampleUnitTest {

    public Context context;

    public SharedPreferences sharedPref;

    public SharedPreferences.Editor editor;

    TestA mTestA;
    String tempStringData = "";

    public void setUp() {

        when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPref);
        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?


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