XML文件
1 28 9 15 16 22 23 28
MainActivity代码
1 package cn.edu.niit.testforgit; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.View; 6 import android.widget.Button; 7 import android.widget.EditText; 8 import android.widget.TextView; 9 10 public class MainActivity extends AppCompatActivity implements View.OnClickListener {11 12 private TextView textView;13 private EditText editText;14 private Button button;15 16 @Override17 protected void onCreate(Bundle savedInstanceState) {18 super.onCreate(savedInstanceState);19 setContentView(R.layout.activity_main);20 sayHello();21 }22 23 public void sayHello() {24 textView = (TextView) findViewById(R.id.textView);25 editText = (EditText) findViewById(R.id.editText);26 button = (Button) findViewById(R.id.button);27 button.setOnClickListener(this);28 }29 30 @Override31 public void onClick(View v) {32 switch (v.getId()) {33 case R.id.button:34 textView.setText("Hello," + editText.getText().toString() + "!");35 editText.setText("");36 break;37 }38 }39 }
MainActivity测试代码MainActivityInstrumentationTest代码
1 package cn.edu.niit.testforgit; 2 3 import android.support.test.filters.LargeTest; 4 import android.support.test.rule.ActivityTestRule; 5 import android.support.test.runner.AndroidJUnit4; 6 7 import org.junit.Rule; 8 import org.junit.Test; 9 import org.junit.runner.RunWith;10 11 import static android.support.test.espresso.Espresso.onView;12 import static android.support.test.espresso.action.ViewActions.click;13 import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;14 import static android.support.test.espresso.action.ViewActions.typeText;15 import static android.support.test.espresso.assertion.ViewAssertions.matches;16 import static android.support.test.espresso.matcher.ViewMatchers.withId;17 import static android.support.test.espresso.matcher.ViewMatchers.withText;18 19 20 /**21 * Created by Wang Yifan on 2017/03/15.22 */23 24 @RunWith(AndroidJUnit4.class)25 @LargeTest26 public class MainActivityInstrumentationTest {27 private static final String STRING_TO_BE_TYPED = "Peter";28 @Rule29 public ActivityTestRulemActivityRule = new ActivityTestRule<>(30 MainActivity.class);31 32 @Test33 public void sayHello() {34 onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());35 onView(withText("Say hello!")).perform(click());36 String expectedText = "Hello," + STRING_TO_BE_TYPED + "!";37 onView(withId(R.id.textView)).check(matches(withText(expectedText)));38 }39 }
测试结果