简体   繁体   中英

Robolectric Testing: can not get the locale

I'm using robolectric framework to test my android project. It is working very well but i couldn't find how to solve the problem:

In my activity class, i have to take the current language as follows:

private void setCurrentLanguageChoosenInRadioGroup() {
    Configuration c = new Configuration(getResources().getConfiguration());
    String locale = c.locale.getLanguage();

    if(locale.equalsIgnoreCase(Constants.DUTCH_LANGUAGE)){          
        radioLanguageGroup.check(dutchButton.getId());
    }
    else if(locale.equalsIgnoreCase(Locale.FRENCH.getLanguage())){
        radioLanguageGroup.check(frenchButton.getId());
    }
    else if(locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage())){
        radioLanguageGroup.check(englishButton.getId());
    }
}

But in the line of "c.locale.getLanguage();" i get nullpointerexception. It is my testing method:

public void setUp() throws Exception {
    activity = new MainActivity();
    activity.onCreate(null); ....

Has anybody a idea what is the problem and how can it be solved?

You are getting an NPE because the locale field is not being set. If you debug and put a breakpoint on the line after you instantiate the Configuration object notice the actual class that loaded. You will see that it is not Configuration , it is ShadowConfiguration .

You can view the source here: https://github.com/pivotal/robolectric/blob/master/src/main/java/org/robolectric/shadows/ShadowConfiguration.java

I'm assuming (not having actually run your code) that getResources().getConfiguration() is either returning null, or doesn't have the locale set. There is a setLocale method in ShadowConfiguration that you could set in your test to manipulate the logic flow in your setCurrentLanguageChoosenInRadioGroup() method.

Updating robolectric to versions 2.x resolves the problem! In versions 0.9.x which is default version on their website, it is not applicable!

Thus, it can be adapted in this way:

Locale loc = new Locale("desired language/country");
Configuration c = new Configuration();
c.setLocale(loc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM