Android TestingAndroid studioAndroid静水流深

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

2015-06-04  本文已影响11726人  TestDevTalk

系列教程

在工程的整体视图上,找到以(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()方法。下面将逐行解释都做了什么:

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

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

Github下载测试源码

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

上一篇下一篇

猜你喜欢

热点阅读