How to mock a SharedPreferences using Mockito

前端 未结 3 1574
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 19:17

    The following example shows how you might create a unit test that uses a mock Context object such as shared preference.

    @RunWith(MockitoJUnitRunner.class)
    public class MProfileTest {
    
       @Mock
       Context mockContext;
       @Mock
       SharedPreferences mockPrefs;
       @Mock
       SharedPreferences.Editor mockEditor;
    
       @Before
       public void before() throws Exception {
    
          Mockito.when(mockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockPrefs);
          Mockito.when(mockContext.getSharedPreferences(anyString(), anyInt()).edit()).thenReturn(mockEditor);
    
          Mockito.when(mockPrefs.getString("YOUR_KEY", null)).thenReturn("YOUR_VALUE");
       }
    
       @Test
       public void anyTest() {
          // Any shared preference you can call
          // Assert.assertTrue();
          String val = _mockPrefs.getString("YOUR_KEY", null); // It returns YOUR_VALUE
       }
    }
    

    If you face any issues on importing mock framework just make sure you have added the depencencies in your app/build.gradle file.

    https://developer.android.com/training/testing/unit-testing/local-unit-tests#setup


    If you want to use real shared prefrence as your device by storing all the data in memory, follow the below code.

    Get the MockSharedPreference.java file from this Gist https://gist.github.com/aslamanver/f74a2b3d450fda251d47a0d38b44edb7

    @Mock
    Context mockContext;
    
    MockSharedPreference mockPrefs;
    MockSharedPreference.Editor mockPrefsEditor;
    
    @Before
    public void before() {
    
        mockPrefs = new MockSharedPreference();
        mockPrefsEditor = mockPrefs.edit();
    
        Mockito.when(mockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockPrefs);
    }
    

提交回复
热议问题