I recently started coding my really first android project using Android Studio 3.1.2 and SDK 19.
I'm writing unit tests for my components at the moment and use Mockito for mocking android API dependant objects. When I wrote the test for my SessionHandler
, a helper class, that manages data stored in SharedPreferences
I came across the problem, that, if I want to check, if e. g. mockEdit.remove("my_key")
was successful, I didn't know, how to mock the behavior in particular.
This is how I prepare my mocking stuff:
private final Context mockedContext = Mockito.mock(Context.class);
private final SharedPreferences mockedPrefs = Mockito.mock(SharedPreferences.class);
private final SharedPreferences.Editor mockEdit = Mockito.mock(SharedPreferences.Editor.class);
private boolean shouldReturnTestUUID = true;
@Before
public void prepareMocks() {
Mockito.when(mockedContext.getSharedPreferences(anyString(), anyInt()).thenReturn(mockedPrefs);
Mockito.when(mockedPrefs.getString("my_key", null)).thenReturn(shouldReturnTestUUID ? "test_UUID" : null);
//this is the one, I got stuck at
Mockito.when(mockEdit.remove("my_key")).thenReturn(mockEdit.putString("my_key", null));
}
The method i'm actually testing:
public synchronized static void removeAppInstanceID(Context context) {
if (appInstanceID != null) {
SharedPreferences sharedPrefs = context.getSharedPreferences("session", Context.MODE_PRIVATE);
sharedPrefs.edit().remove("my_key").apply();
}
}
The test method:
@Test
public void canRemoveUUID() {
shouldReturnTestUUID = false;
SessionHandler.removeAppInstanceID(mockedContext);
assertNull(mockedPreferences.getString("my_key", null));
shouldReturnTestUUID = true;
}
If I try to run this test I get an UnfinishedStubbingException referring to the line where I want to mock mockEdit.remove("my_key")
. Seemingly, the stub doesn't know what to do with mockEdit.putString("my_key", null);
.
So my question is, how to mock this method, so I can call mockedPrefs.getString("my_key")
and check if the returned value is null
? Thanks in forward.