skip to Main Content

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?

2

Answers


  1. Your test class method looks a little bit weird.

    You are using following method calls within TestA constructor

    mSharedPref = context.getSharedPreferences(context.getString(R.string.shrf_file_key), Context.MODE_PRIVATE);
    

    Therefore you should mock following method calls

     context.getSharedPreferences(...)
     context.getString(...)
    

    like this

     when(context.getString(eq(R.string.shrf_file_key)).thenReturn(tempStringData);  
     when(context.getSharedPreferences(eq(tempStringData), eqInt(Context.MODE_PRIVATE)).thenReturn(sharedPref);
    
    Login or Signup to reply.
  2. 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search