android.content.res.Configuration类型的模拟对象,并为其分配一个区域设置



我有一个类,我正在尝试检索设备的国家/地区:

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

其中context的类型为:android.content.Context

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

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

在此基础上,我正在访问字段locale,它的类型为java.util.Locale

在一个单元测试中,我试图模拟整个上下文:

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类型的对象并为其提供区域设置呢?

这就是使用Mockito的方法,我也在那里发布了我的答案。

示例

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));
}
}

系统输出

en_CA
Process finished with exit code 0

Mockito Doc

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

最新更新