`

使用Espresso作为测试工具

 
阅读更多
   Youtube上面关于Espresso单独出了三期的内容讲解Espresso作为整合Unit Test, Instrument Test,end-to-end test等。我试了一下,感觉还不错。

   官网地址:https://google.github.io/android-testing-support-library/docs/index.html

   GitHub:https://github.com/googlesamples/android-testing/tree/master/ui/espresso


   我在一个已有的项目里面加入测试用例代码

   1. 引入依赖包(使用2.2.2会需要23.1.1,这边会有ERROR曝出, 故降未2.2.1)

    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    androidTestCompile 'com.android.support.test:runner:0.4.1'
    androidTestCompile 'com.android.support.test:rules:0.4.1'


   2. 设置编译配置
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"


   3.针对登录页面的测试,三个测试case,测试用户名不能为空,测试密码不能为空和输入用户名和密码测试正确性
/**
 * 登录测试
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginFragmentText {

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

    private MainActivity mainActivity;

    //这里进入以后 有一个主Fragment, 下面是4个按钮,点击其中一个进入登录页面
    @Before
    public void switchToLogin () {
        LogUtils.debug("switchToLogin...");
        onView(withId(R.id.btnProfileID)).perform(click());

        mainActivity = mActivityRule.getActivity();
    }

    //提示都是Toast弹窗提示(下同)
    @Test
    public void testUsernameNotEmpty() {
        onView(withId(R.id.login_login_btn)).perform(click());
        
        onView(withText("用户名不能为空")).inRoot(withDecorView(not(mainActivity.getWindow().getDecorView()))).check(matches(isDisplayed()));
    }

    @Test
    public void testPasswordNotEmpty() {

        //注入用户名
        onView(withId(R.id.login_username)).perform(click(), clearText(), typeText("1234567"), closeSoftKeyboard());

        //点击登录按钮
        onView(withId(R.id.login_login_btn)).perform(click());
        //弹窗提示
        onView(withText("密码不能为空")).inRoot(withDecorView(not(mainActivity.getWindow().getDecorView()))).check(matches(isDisplayed()));
    }

    @Test
    public void testLogin () {
        //注入用户名
        onView(withId(R.id.login_username)).perform(typeText("1234567"), closeSoftKeyboard());
        //注入密码
        onView(withId(R.id.login_password)).perform(typeText("123456"), closeSoftKeyboard());
        //点击登录按钮
        onView(withId(R.id.login_login_btn)).perform(click());
        //弹窗提示 登录成功
        onView(withText("登录成功")).inRoot(withDecorView(not(mainActivity.getWindow().getDecorView()))).check(matches(isDisplayed()));
    }
}


测试的时候,尤其是EditText输入框容易受到手机安装的输入法的影响,可能会出现输入不进入的情况, 这个时候可以用Thread.sleep(XXXX)来暂停捕获画面,比以前的Selenium好用多了
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics