Set a custom context in AndroidTestCase
I'm trying to test my custom ContentProvider
which only updates an item at a certain point in time.
In order to test the shouldUpdate
branch, I need to revert time and set a custom date in my application. I couldn't stub out System.currentTimeMi开发者_StackOverflowllis()
, so I put a method in my Application object, and I'm trying to setContext()
in AndroidTestCase
like this.
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);
}
However, when I call getApplicationContext().currentTimeMillis()
in my provider, it returns the real implementation of the method, which is System.currentTimeMillis()
and not my custom date time that I set in the AndroidTestCase
.
What am I doing wrong?
p.s. I know about ProviderTestCase2, but I'm also accessing SharedPreferences in my provider, and for those ProviderTestCase2 returns null. That's why I'm using AndroidTestCase.
精彩评论