首页 > 解决方案 > 模拟 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并给它一个语言环境呢?

标签: javaandroidmockito

解决方案


这就是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


推荐阅读