如何从测试中访问字符串资源?

问题描述 投票:0回答:3

我有一个android项目。我想在junit中测试它。在资源中,在

strings.xml
内部,我有一个名为
labels_array
的字符串数组。如何从 junit 中的测试方法访问(获取)这个字符串数组?

在测试课上我有

    @Rule
    public ActivityScenarioRule mActivityRule = new ActivityScenarioRule<>(
            MainActivity.class);


    @Test
    public void fooTest() {
        ActivityScenario scenario = mActivityRule.getScenario();
}

但是我如何使用这些规则和方法来从方法内部访问字符串数组

fooTest

android testing junit resources
3个回答
10
投票

既然要获取字符串数组的真实值,可以使用:

final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
@ArrayRes final String[] labelsArray = context.getResources().getStringArray(R.array.labels_array);

1
投票

您可以使用模拟来做到这一点。我认为以下链接之一可能是您请求的解决方案。

https://medium.com/android-testing-daily/unit-testing-xml-resources-7387447f9ef7

Android 单元测试,从资源中获取字符串


0
投票

Kotlin 相当于已接受的答案:

val context = InstrumentationRegistry.getInstrumentation().targetContext
context.resources.getString(R.array.labels_array)
© www.soinside.com 2019 - 2024. All rights reserved.