java - 模拟 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!");
}
Configuration
或者,我尝试用 Mockito 模拟整个班级:
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
来自java.lang.NoSuchMethodError: android.content.res.Configuration.setLocale(Ljava/util/Locale;)V
推荐阅读
- reactjs - 如何使用 React 从 mongoose 读取 api
- laravel - 如何通过post方法从邮递员的原始数据中保存和下载视频文件等文件
- mysql - 如何在 MYSQL 中为每个提交日期选择最高贡献者
- javascript - 如何在 Cloud Firestore 中有效地获取集合的所有文档及其子集合
- python - 如何检查元素h2是否包含文本
- python - 如何使用 Mayavi 在 python 中为 3D 数据制作动画
- html - 已选中和未选中复选框的值传递给 Django 视图
- excel - 搜索错误,填充数组并呈现类似于视图的枢轴
- php - 使用 php 每 10 秒刷新一次 div 或函数数据
- python - python中的id_generator打印10个id号