小编ant*_*_st的帖子

使用 Mockito 模拟 PreferenceManager

我是 Android 单元测试的新手,我想在现有项目中添加一些单元测试。我正在使用 MVP 设计架构。在我的演示者内部,我有一个调用PreferenceManager以获取默认值,SharedPrefences但它始终返回 null。我在 stackoverflow 上遵循了一些关于如何模拟的教程和建议PreferenceManagerSharedPreferences但我无法让它工作。这是我的演讲者课

@RunWith(MockitoJUnitRunner.class)
public class SettingsPresenterTest {
    @Mock
    private SettingsView mView;
    @Mock
    private LocalConfiguration conf;
    private SettingsPresenter mPresenter;

    public SettingsPresenterTest() {
        super();
    }

    @Before
    public void startUp() throws Exception {
        MockitoAnnotations.initMocks(LocalConfiguration.class);
        MockitoAnnotations.initMocks(PreferenceManager.class);


        mPresenter = new SettingsPresenter(mView);


        final SharedPreferences sharedPrefs = 
        Mockito.mock(SharedPreferences.class);
        final Context context = Mockito.mock(Context.class);

       Mockito.when(PreferenceManager.getDefaultSharedPreferences(context)).
       thenReturn(sharedPrefs);
    }


    @Test
    public void notificationsEnabledClicked() throws Exception {
        boolean notifsEnabled = false;
        mPresenter.notificationsEnabledClicked(notifsEnabled);

        Mockito.verify(mView).setNotificationsView(notifsEnabled);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是SharedPreferences …

tdd junit android unit-testing mockito

5
推荐指数
1
解决办法
1048
查看次数

标签 统计

android ×1

junit ×1

mockito ×1

tdd ×1

unit-testing ×1