要为Android测试添加单独的资源,可以按照以下步骤进行操作:
src/androidTest
目录下,创建一个与res
目录对应的目录结构,例如src/androidTest/res
。src/androidTest/res
目录下创建与主项目中的res
目录对应的子目录结构,例如src/androidTest/res/layout
。src/androidTest/res/layout
目录下创建一个名为test_layout.xml
的布局文件。@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule
public ActivityScenarioRule activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class);
@Test
public void testLayout() {
onView(withId(R.id.text_view)).check(matches(withText(R.string.app_name)));
onView(withId(R.id.test_button)).perform(click());
onView(withId(R.id.test_text)).check(matches(withText(R.string.test_string)));
onView(withId(R.id.test_layout)).check(matches(isDisplayed()));
}
}
在上面的示例代码中,我们使用了R.string.app_name
和R.string.test_string
这两个资源字符串,并使用R.id.test_layout
这个资源ID来检查布局是否显示。
请确保在测试类中导入正确的资源文件R类,例如import com.example.myapp.R;
。
这样,就可以为Android测试添加单独的资源了。