如何在开始 Espresso 测试之前准备数据库数据?
How to prepare DB data before starting Espresso tests?
数据库:SQLite
Table : 联系人
浓缩咖啡测试:
@Test
public void testBlock() {
onData(anything()).inAdapterView(withId(R.id.container_ListView)).atPosition(0).onChildView(withText(R.string.block_user))
.perform(click());
}
并且测试成功通过。但只有在开始之前,联系人的状态为 unblock(db table 中的列 Status),它才会成功。所以我需要(在开始测试之前)将此 Contact 更新为状态 unblock。我怎样才能做到这一点?或者有人对此有更好的解决方案吗?
您可以在 @Before
方法中或在开始 activity 之前在您的测试用例中执行此操作。
首先,您需要将 activity 规则更改为:
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
MainActivity.class, false, false);
注意最后一个 false
标志,这表示您的活动不会在测试开始时自动启动。
然后在你的测试中class你可以添加这个方法:
@Before
public static void PrepareDatabase() {
// Instantiate your Service that performs an action on the database
// give it this context: InstrumentationRegistry.getTargetContext();
// For example the code could look like this:
DatabaseHelper(InstrumentationRegistry.getTargetContext()).setYourValue();
mActivityRule.launchActivity(null); //launches the test activity
}
然后正常写你的测试。此代码对您的数据库执行一些操作,然后启动您的 activity 进行测试。您也可以将其传递到您的测试方法中,而不是在 @Before 方法中。
数据库:SQLite
Table : 联系人
浓缩咖啡测试:
@Test
public void testBlock() {
onData(anything()).inAdapterView(withId(R.id.container_ListView)).atPosition(0).onChildView(withText(R.string.block_user))
.perform(click());
}
并且测试成功通过。但只有在开始之前,联系人的状态为 unblock(db table 中的列 Status),它才会成功。所以我需要(在开始测试之前)将此 Contact 更新为状态 unblock。我怎样才能做到这一点?或者有人对此有更好的解决方案吗?
您可以在 @Before
方法中或在开始 activity 之前在您的测试用例中执行此操作。
首先,您需要将 activity 规则更改为:
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
MainActivity.class, false, false);
注意最后一个 false
标志,这表示您的活动不会在测试开始时自动启动。
然后在你的测试中class你可以添加这个方法:
@Before
public static void PrepareDatabase() {
// Instantiate your Service that performs an action on the database
// give it this context: InstrumentationRegistry.getTargetContext();
// For example the code could look like this:
DatabaseHelper(InstrumentationRegistry.getTargetContext()).setYourValue();
mActivityRule.launchActivity(null); //launches the test activity
}
然后正常写你的测试。此代码对您的数据库执行一些操作,然后启动您的 activity 进行测试。您也可以将其传递到您的测试方法中,而不是在 @Before 方法中。