我有一个android项目。我想在junit中测试它。在资源中,在
strings.xml
内部,我有一个名为 labels_array
的字符串数组。如何从 junit 中的测试方法访问(获取)这个字符串数组?
在测试课上我有
@Rule
public ActivityScenarioRule mActivityRule = new ActivityScenarioRule<>(
MainActivity.class);
和
@Test
public void fooTest() {
ActivityScenario scenario = mActivityRule.getScenario();
}
但是我如何使用这些规则和方法来从方法内部访问字符串数组
fooTest
?
既然要获取字符串数组的真实值,可以使用:
final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
@ArrayRes final String[] labelsArray = context.getResources().getStringArray(R.array.labels_array);
您可以使用模拟来做到这一点。我认为以下链接之一可能是您请求的解决方案。
https://medium.com/android-testing-daily/unit-testing-xml-resources-7387447f9ef7
或
Kotlin 相当于已接受的答案:
val context = InstrumentationRegistry.getInstrumentation().targetContext
context.resources.getString(R.array.labels_array)