3

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!

earthling
  • 5,084
  • 9
  • 46
  • 90
  • Hmm, what does the actual date method you mentioned look like? (The code whose output should be affected by the `en_GB` locale.) – Jonik Nov 20 '13 at 19:30

1 Answers1

0

When you change the locale you are specifying the full locale "en_GB". This does not work. According to the documentation you need to specify the language and the country separately

Locale locale = new Locale("en","GB");

From my experience if you specify an incorrect locale, the device will simply use the default locale

QuantumTiger
  • 970
  • 1
  • 10
  • 22