1

我正在尝试测试我的自定义ContentProvider,它只在某个时间点更新一个项目。

为了测试shouldUpdate分支,我需要在我的应用程序中恢复时间并设置自定义日期。我无法 stub out System.currentTimeMillis(),所以我在我的 Application 对象中放置了一个方法,我正在尝试setContext()这样AndroidTestCase

private void setContextDate(final Date myCustomDate){
    final Context baseContext = getContext();
    final ContentResolver contentResolver = baseContext.getContentResolver();
    final MyApplication myApp = new MyApplication() {
        @Override
        public long currentTimeMillis(){
            return myCustomDate.getTime();
            // This normally returns System.currentTimeMillis();
        }
        @Override
        public Context getBaseContext(){
            return baseContext;
        }
        @Override
        public ContentResolver getContentResolver(){
            return contentResolver;
        }
    };
    ContextWrapper contextWrapper = new ContextWrapper(baseContext) {
        @Override
        public Context getApplicationContext(){
            return myApp;
        }

    };
    setContext(contextWrapper);

}

但是,当我调用getApplicationContext().currentTimeMillis()我的提供程序时,它会返回该方法的真正实现,System.currentTimeMillis()而不是我在AndroidTestCase.

我究竟做错了什么?

ps 我知道 ProviderTestCase2,但我也在我的提供者中访问 SharedPreferences,对于那些 ProviderTestCase2 返回 null。这就是我使用 AndroidTestCase 的原因。

4

0 回答 0