Android单元测试

代码案列


package com.example.android.testing.espresso.BasicSample;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
...

@RunWith(AndroidJUnit4.class)
@LargeTest
public class ChangeTextBehaviorTest {

    private String mStringToBetyped;

    **第一步:把要测试的Activity作为ActivityTestRule的泛型,比如我这里是MainActivity**
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class);
**before注解表示在进行测试之前,可以做一些初始化的动作,也可以不写**
    @Before
    public void initValidString() {
        // Specify a valid string.
        mStringToBetyped = "Espresso";
    }

    @Test
    public void changeText_sameActivity() {
        // Type text and then press the button.
        onView(withId(R.id.editTextUserInput))
                .perform(typeText(mStringToBetyped), closeSoftKeyboard());
        onView(withId(R.id.changeTextBt)).perform(click());

        // Check that the text was changed.
        onView(withId(R.id.textToBeChanged))
                .check(matches(withText(mStringToBetyped)));
    }
}

对UI界面的测试,主要就是找到View,然后执行action,最后check 结果是否正确

怎么找到view呢

为了找到view,你需要调用onView方法并且传递一个指定了view的viewMatcher的对象。详细指定一个View  Matcher的细节会在后面讲解。onView方法执行完毕,会返回一个ViewInterface的对象,你就可以拿这个对象和view进行交互测试。通过onView方法找不到布局中的recyclerView,需要通过onData方法来实现,后天会详细介绍。
To find the view, call the onView() method and pass in a view matcher that specifies the view that you are targeting. This is described in more detail in Specifying a View Matcher. The onView() method returns a ViewInteraction object that allows your test to interact with the view. However, calling the onView() method may not work if you want to locate a view in an RecyclerView layout. In this case, follow the instructions in Locating a view in an AdapterView instead
**下面的代码片段,向你展示写一个简单的测试,访问EditText控件,向它里面输入text文本,输入完毕关闭虚拟键盘,最后执行按钮的点击的事件**
The following code snippet shows how you might write a test that accesses an EditText field, enters a string of text, closes the virtual keyboard, and then performs a button click.
public void testChangeText_sameActivity() {
    // Type text and then press the button.
    onView(withId(R.id.editTextUserInput))
            .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
    onView(withId(R.id.changeTextButton)).perform(click());

    // Check that the text was changed.
    ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值