美文网首页Android TestingAndroid studioAndroid静水流深
在Android Studio中进行单元测试和UI测试 - 8.

在Android Studio中进行单元测试和UI测试 - 8.

作者: TestDevTalk | 来源:发表于2015-06-04 13:49 被阅读11726次

系列教程

在工程的整体视图上,找到以(androidTest)后缀结尾的包名并创建一个新的Java类。可以将它命名为MainActivityInstrumentationTest,将如下代码粘贴过去。

*** MainActivityInstrumentationTest.java*

package com.example.testing.testingexample;

import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.action.ViewActions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;

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

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

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

    private static final String STRING_TO_BE_TYPED = "Peter";

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

    @Test
    public void sayHello(){
        onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); //line 1

        onView(withText("Say hello!")).perform(click()); //line 2

        String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!";
        onView(withId(R.id.textView)).check(matches(withText(expectedText))); //line 3
    }

}

测试类通过AndroidJUnitRunner运行,并执行sayHello()方法。下面将逐行解释都做了什么:

  • 1.首先,找到ID为editText的view,输入Peter,然后关闭键盘;
  • 2.接下来,点击Say hello!的View,我们没有在布局的XML中为这个Button设置id,因此,通过搜索它上面的文字来找到它;
  • 3.最后,将TextView上的文本同预期结果对比,如果一致则测试通过;

你也可以右键点击域名运行测试,选择Run>MainActivityInstrume...(第二个带Android图标的)

这样就会在模拟器或者连接的设备上运行测试,你可以在手机屏幕上看到被执行的动作(比如在EditText上打字)。最后会在Android Studio输出通过和失败的测试结果。

Github下载测试源码

下一篇:在Android Studio中进行单元测试和UI测试 - 9.祝贺!

相关文章

网友评论

  • 花蝶扇:onView(withId(R.id.textView)).check(matches(withText(expectedText))); 这行出错android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: is "World"' doesn't match the selected view.
    Expected: with text: is "World"
  • chiaro:这个地方应该加个注意。如果报错:
    junit.framework.AssertionFailedError: No tests found in
    应该在gradle的defaultConfig中加一句:
    testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'

本文标题:在Android Studio中进行单元测试和UI测试 - 8.

本文链接:https://www.haomeiwen.com/subject/lyydqttx.html