Espresso + Junit4 - 在运行所有测试之前登录一次

时间:2016-06-16 05:37:23

标签: android junit4 android-espresso

我想为我的一个应用程序编写一些自动化测试。所有功能都需要登录。

所以,我已经编写了测试,但是对于每个测试,它都在进行登录和测试功能。无论如何,这有助于我只登录一次然后运行所有测试吗?

最简单的方法是只用一种测试方法编写所有测试。但我认为实现这一目标将是一种丑陋的方式。任何更干净的解决方案,测试只会登录一次然后运行测试集。

以下是我的测试代码:

@RunWith(AndroidJUnit4.class)
public class AllDisabledTest {
    public static final String USER_NAME = "all_disabled";
    public static final String DISPLAY_NAME = "All Disabled";
    public static final String PASSWORD = "1234";

    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(
            LoginActivity.class);

    @Before
    public void loginToApp(){

        onView(withId(R.id.edit_email)).perform(replaceText(USER_NAME));
        onView(withId(R.id.edit_password)).perform(replaceText(PASSWORD));

        onView(withId(R.id.login_button)).perform(click());
    }

    @Test
    public void checkIfFoodItemAddedToCart(){
        onData(anything()).inAdapterView(withId(R.id.menu_item_grid)).atPosition(2).perform(click());

        onData(anything()).inAdapterView(withId(R.id.listview)).atPosition(0).onChildView(withId(R.id.item_name)).check(matches(withText("BLUEITEM")));
    }
}

提前谢谢你:)。

1 个答案:

答案 0 :(得分:3)

您可以使用@BeforeClass和@AfterClass注释的方法。

@RunWith(AndroidJUnit4.class)
public class AllDisabledTest {
    public static final String USER_NAME = "all_disabled";
    public static final String DISPLAY_NAME = "All Disabled";
    public static final String PASSWORD = "1234";

    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(
            LoginActivity.class);
    }

    @BeforeClass
    public static void setUpBeforeClass() {
        // do login stuff here
    }

    @AfterClass
    public static void tearDownAfterClass() {
        // ...
    }

    // ...
}

注意:@BeforeClass和@AfterClass方法必须是静态的。