I'm a .NET dev new to Java and Android. I'm beginning with the platform by working on some unit tests and I have a date method I want to test that takes the current context
as a parameter. I want to moc this context and specify a locale of my choosing independent of the current device setting.
Is this possible and can anyone tell me how to do this?
I tried creating a custom class that extends Application and override the onCreate
method setting the locale there. I then passed it in my method by calling the getApplicationContext()
method, but that didn't seem to do the job. Here's what I tried:
class UKApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
Locale locale = new Locale("en_GB");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}
I also tried setting the configuration of the context which seems closer, but when I extracted the date format, it doesn't appear to affect the date format.
Locale locale = new Locale("en_GB");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
mContext.getResources().updateConfiguration(config, mContext.getResources().getDisplayMetrics());
myStaticClass.methodToTest(mContext);
Any tips?
Here's the code that is using the context to get the date format. Pattern always seems to come out as MM/dd/yyyy:
final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
if (shortDateFormat instanceof SimpleDateFormat) {
final String pattern = ((SimpleDateFormat) shortDateFormat).toPattern();
thank you!