How to mock a SharedPreferences using Mockito
So, because SharedPreferences comes from your context, it’s easy: final SharedPreferences sharedPrefs = Mockito.mock(SharedPreferences.class); final Context context = Mockito.mock(Context.class); Mockito.when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPrefs); // no use context for example, for getValidToken(Context context), the test could be: @Before public void before() throws Exception { this.sharedPrefs = Mockito.mock(SharedPreferences.class); this.context = Mockito.mock(Context.class); Mockito.when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPrefs); } @Test public void testGetValidToken() throws … Read more