#单元测试

1、首先是配置环境
放在app下的build.gradle里的defaultConfig {}中
、、、
//add for test
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
、、、
下面段放在build.gradle里的dependencies {}中
//add for test
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
}
当然如果本身配置高的话,可能会自动的配置测试环境

2、xml布局
、、、

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView"
    android:hint="Enter your name here" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText"
    android:onClick="sayHello"
    />
、、、

3、MainActivity
、、、
package com.edu.niit.ceshi;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void sayHello(View v) {
    TextView textView = (TextView) findViewById(R.id.textView);
    EditText editText = (EditText) findViewById(R.id.editText);
    textView.setText("Hello," + editText.getText().toString() + "!");
}

}
、、、

4、测试程序

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());

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

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

、、、
其中要注意导包
本人在导包的过程中遇到了的困难,按快捷键Alr+Enter显示不出来需要导包的可能,查阅了资料,还是找不到原因,正在琢磨中,后续加上问题所在和解决方案。
刚重新打开了下软件,再次使用快捷键导包轻而易举的就导出来了,我也不知道为什么,可能是软件的加载问题吧。

原文地址:https://www.cnblogs.com/zjh55/p/6559433.html