Espresso + Junit4 - login once before running all test

南笙酒味 提交于 2019-12-23 14:51:38

问题


I want to write some automated test for one of my application. All of the functionality requires login.

So, i have written test, but for each test, it is doing login and testing the functionality. Is there anyway which will help me to login only once and then run all test?

Easiest way would be to write all test in only one test method. But i think it would be ugly way to achieve that. Any cleaner solution so, test will login only once and then run set of test.

Following is my test code:

@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")));
    }
}

Thank you in advance :).


回答1:


You can use methods with @BeforeClass and @AfterClass annotations.

@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() {
        // ...
    }

    // ...
}

Note: @BeforeClass and @AfterClass methods must be static.



来源:https://stackoverflow.com/questions/37850656/espresso-junit4-login-once-before-running-all-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!