如何在开始Espresso测试之前准备DB数据?

时间:2017-03-19 16:07:02

标签: android android-espresso android-testing

DB:SQLite

表:联系

Espresso测试:

@Test
public void testBlock() {
   onData(anything()).inAdapterView(withId(R.id.container_ListView)).atPosition(0).onChildView(withText(R.string.block_user))
            .perform(click());
}

测试成功通过。但只有在开始联系之前状态为取消阻止(db表中的列状态)时才会成功。所以我需要(在开始测试之前)将此联系人更新为状态取消阻止。我怎样才能做到这一点?或者有人为此提供更好的解决方案吗?

1 个答案:

答案 0 :(得分:5)

在开始活动之前,您可以在@Before方法或测试用例中执行此操作。

首先,您需要将活动规则更改为:

    @Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
        MainActivity.class, false, false);

请注意最后一个false标记,这表示您的活动在测试开始时不会自动启动。

然后在您的测试类中添加此方法:

 @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
}

然后通常写你的测试。此代码对您的数据库执行某些操作,然后启动您的测试活动。您也可以将其传递给测试方法而不是@Before方法。