模拟android.content.res.Configuration类型的对象并为其指定一个语言环境

我有一个class级,我试图检索设备的国家:

context.getResources().getConfiguration().locale.getCountry(); 

context的类型为: android.content.Context

所以在这里, context.getResources()返回一个android.content.res.Resources类型的对象。

在该对象上,调用getConfiguration() ,返回android.content.res.Configuration类型的对象。

在那,我正在访问字段locale ,它是java.util.Locale类型。

在unit testing中,我试图模拟整个上下文:

 Locale locale = new Locale(DEFAULT_LANGUAGE, DEFAULT_COUNTRY); configuration = new Configuration(); configuration.setLocale(locale); 

但是,我收到错误,因为setLocale实现为:

 public void setLocale(Locale loc) { throw new RuntimeException("Stub!"); } 

或者,我尝试使用Mockito模拟整个Configuration类:

 mock(Configuration.class); 

但是,我无法做到这一点,因为该类被宣布为final

那么,我如何模拟android.content.res.Configuration类型的对象并给它一个语言环境?

这就是如何使用MockitoMockito那里重新发布我的答案。

 import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.LocaleList; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.util.Locale; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class Test2 { @Mock Context mMockContext; @Test public void getLocal() { Resources resources = Mockito.mock(Resources.class); when(mMockContext.getResources()).thenReturn(resources); Configuration configuration = Mockito.mock(Configuration.class); when(mMockContext.getResources().getConfiguration()).thenReturn(configuration); LocaleList localeList = Mockito.mock(LocaleList.class); when(mMockContext.getResources().getConfiguration().getLocales()).thenReturn(localeList); when(mMockContext.getResources().getConfiguration().getLocales().get(0)).thenReturn(Locale.CANADA); System.out.println(mMockContext.getResources().getConfiguration().getLocales().get(0)); } } 

System.out的

 en_CA Process finished with exit code 0 

Mockito Doc

来自java.lang.NoSuchMethodError:android.content.res.Configuration.setLocale(Ljava / util / Locale;)V