Android测试驱动开发实践1
|
package com.bjcic.wkj.test;
import com.bjcic.wkj.MainActivity;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
public MainActivityTest() {
super(MainActivity.class);
}
/**
* 每个测试用例开始运行前必须执行的代码
*/
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
activity = getActivity();
}
/**
* 每个测试用例运行结束时必须执行的代码
*/
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* 测试界面上标题文字为:维康街
*/
public void testTemp001() {
titleTxtv = (TextView)activity.findViewById(com.bjcic.wkj.R.id.j_titleTxtv);
assertEquals(activity.getString(com.bjcic.wkj.R.string.welcome_msg), titleTxtv.getText());
}
private Activity activity = null;
private TextView titleTxtv = null;
}
|
在WkjTest工程中,选中MainActivityTest类,点右键,选择Run As....然后选Android JUnit Test,在随后弹出的界面选择测试设备,运行程序后,在Junit视图会显示,执行了test001测试用例,并且该测试用例失败了,这正是我们目前所需要的结果。
|
package com.bjcic.wkj;
import android.app.Application;
public class AppModel extends Application {
// 生命周期方法开始
public void onCreate() {
super.onCreate();
welcomeMsg = getString(R.string.welcome_msg);
}
public void onTerminate() {
super.onTerminate();
}
// 生命周期方法结束
private String welcomeMsg = null;
public String getWelcomeMsg() {
return welcomeMsg;
}
public void setWelcomeMsg(String welcomeMsg) {
this.welcomeMsg = welcomeMsg;
}
}
在MainActivity中添加如下代码:
[java] view plaincopy
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appModel = (AppModel)getApplication();
}
@Override
public void onResume() {
super.onResume();
((TextView)findViewById(R.id.j_titleTxtv)).setText(appModel.getWelcomeMsg());
}
private AppModel appModel = null;
|
|
<application
android:allowBackup="true"
android:name=".AppModel"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
|