Demo1

Activity代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.yimo.myapplication.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Enter your name"
android:ems="10"
android:hint="Enter your name"
android:id="@+id/editText" />

<Button
android:text="sayHello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText"
android:layout_toEndOf="@+id/textView"
android:layout_gravity="center"
android:onClick="sayHello"
android:id="@+id/button" />
</LinearLayout>



Java代码:
public class MainActivity extends AppCompatActivity {


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

}

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


}


Test代码:
package com.example.yimo.myapplication;

import android.support.test.espresso.ViewAssertion;
import android.support.test.rule.ActivityTestRule;
import android.view.View;

import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;

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.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;
import static org.junit.Assert.*;

/**
* Created by yimo on 2017/3/18.
*/
public class MainActivityTest {
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));

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




}
原文地址:https://www.cnblogs.com/distanc/p/6579352.html