android-testing开始使用android测试


备注

本节概述了android-testing是什么,以及开发人员为什么要使用它。

它还应该提到android-testing中的任何大型主题,并链接到相关主题。由于android-testing文档是新的,您可能需要创建这些相关主题的初始版本。

测试类型

Android测试基于JUnit,您可以将它们作为JVM上的本地单元测试或Android设备上的检测测试运行。此页面介绍了构建Android测试的概念和工具

  • 本地单元测试(位于module-name / src / test / java /)
  • 检测测试(位于module-name / src / androidTest / java /)

本地单元测试JUnit

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

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

    @Test
    public void sayHello(){
        onView(withText("Say hello!")).perform(click());

        onView(withId(R.id.textView)).check(matches(withText("Hello, World!")));
    }
}
 

检测测试示例依赖项{androidTestCompile'c​​om.android.support:support-annotations:24.0.0'androidTestCompile'c​​om.android.support.test:runner:0.5'androidTestCompile'c​​om.android.support.test:rules:0.5'/ /可选 - Hamcrest库androidTestCompile'org.hamcrest:hamcrest-library:1.3'//可选 - 使用Espresso androidTestCompile进行UI测试'com.android.support.test.espresso:espresso-core:2.2.2'//可选 - 使用UI Automator进行UI测试androidTestCompile'c​​om.android.support.test.uiautomator:uiautomator-v18:2.1.2'}

android {defaultConfig {testInstrumentationRunner“android.support.test.runner.AndroidJUnitRunner”}}

仪表单元测试类

import android.os.Parcel;
import android.support.test.runner.AndroidJUnit4;
import android.util.Pair;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class LogHistoryAndroidUnitTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;
    private LogHistory mLogHistory;

    @Before
    public void createLogHistory() {
        mLogHistory = new LogHistory();
    }

    @Test
    public void logHistory_ParcelableWriteRead() {
        // Set up the Parcelable object to send and receive.
        mLogHistory.addEntry(TEST_STRING, TEST_LONG);

        // Write the data.
        Parcel parcel = Parcel.obtain();
        mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0);

        // Read the data.
        LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);
        List<Pair<String, Long>> createdFromParcelData = createdFromParcel.getData();

        // Verify that the received data is correct.
        assertThat(createdFromParcelData.size(), is(1));
        assertThat(createdFromParcelData.get(0).first, is(TEST_STRING));
        assertThat(createdFromParcelData.get(0).second, is(TEST_LONG));
    }
}