How to mock a SharedPreferences using Mockito

前端 未结 3 1575
夕颜
夕颜 2021-01-03 18:24

I have just read about Unit Instrumented Testing in Android and I wonder how I can mock a SharedPreferences without any SharedPreferencesHelper class on it like here

3条回答
  •  自闭症患者
    2021-01-03 19:24

    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 Exception {
        Mockito.when(sharedPrefs.getString(anyString(), anyString())).thenReturn("foobar");
        assertEquals("foobar", Auth.getValidToken(context));
        // maybe add some verify();
    }
    

提交回复
热议问题