#单元测试

1、首先是配置环境(如果  targetSdkVersion为 24或 targetSdkVersion为 23)

放在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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Word"
android:id="@+id/textView" />


<EditText

android:hint="Enter your name here"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignBaseline="@+id/button"
android:layout_alignBottom="@+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<Button

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Say Hello"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="51dp" />

、、、

3、MainActivity
、、、

package com.example.lenovo.myapplication1;

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

public class MainActivity extends AppCompatActivity {

private TextView textView;

private EditText editText;

private Button button;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);



textView= (TextView) findViewById(R.id.textView);

editText= (EditText) findViewById(R.id.editText);

button= (Button) findViewById(R.id.button);



button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

editText.setText(textView.getText().toString());

}

});

}

}

4、测试程序

private static final String STRING_TO_BE_TYPED = "Peter";

、、、
package com.example.lenovo.myapplication1;

import org.junit.Rule;
import org.junit.Test;

/**
* Created by lenovo on 2017-3-16.
*/
@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)));
}
、、、
然后就没然后了。。。

 

 
posted @ 2017-03-16 18:26  魏静  阅读(136)  评论(2编辑  收藏  举报