我尝试编写一个junit测试用例来选择列表项和意图下一个活动,但我不知道如何通过junit编码来模拟这个用户操作。有人可以帮忙吗?
另外我想问一下,是否有任何材料教授函数或语法来模拟junit中的不同用户操作?
以下是我学校教程笔记中的一个示例,我想做类似这样的事情,但是在listview项目上。
public void testKilosToPounds() {
/* INTERACTIONS */
TouchUtils.tapView(this, textKilos); // tap the EditText textKilos
sendKeys("1"); // sent the number 1
TouchUtils.clickView(this, buttonPounds); // click the button buttonPounds
/*CHECK THE RESULT*/
double pounds;
try {
pounds = Double.parseDouble(textPounds.getText().toString());
} catch (NumberFormatException e) {
pounds = -1;
}
//JUnit Assert equals
// message expected actual delta for comparing doubles
assertEquals("1 kilo is 2.20462262 pounds", 2.20462262, pounds, DELTA);
}
答案 0 :(得分:1)
您可以点击ListView
中的特定行,首先获取包含该子项的视图,然后将该视图传递到TouchUtils.clickView
。
如果您有ListView view
和ActivityInstrumentationTestCase2 this
,并且想在视图中点击位置p
:
TouchUtils.clickView(this, view.getChildAt(p));
您可能还想检查视图是否实际在屏幕上。
答案 1 :(得分:1)
我在过去几个月一直在研究JUnit来测试android应用程序。所以我现在能够测试几乎像webservices和views这样的东西。无论如何,我正在共享我的代码来测试listview,点击项目并在下一个活动(InfoActivity)中检查我使用意图发送的数据。 InfoActivity是我从ListActivity发送点击项目数据的活动。
public class ListActivityTest extends ActivityInstrumentationTestCase2<ListActivity> {
private Activity activity;
private ListView lv;
private InfoActivity contextInfoActivity;
private TextView tvInfo;
public ListActivityTest(){
super(ListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
activity = (ListActivity)getActivity();
lv = (ListView)activity.findViewById(R.id.lv);
}
public void testCase1(){
assertNotNull(activity);
assertNotNull(lv);
}
public void testCase2(){
Instrumentation instrumentation = getInstrumentation();
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(InfoActivity.class.getName(), null, false);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
lv.performItemClick(lv,4,0);
//lv is listview,4 is item position,0 is default id
}
});
Activity currentActivity = getInstrumentation().waitForMonitor(monitor);
contextInfoActivity = (InfoActivity) currentActivity;
assertNotNull(contextInfoActivity);
tvInfo = (TextView)contextInfoActivity.findViewById(R.id.tvInfo);
assertNotNull(tvInfo);
assertEquals("Karan",tvInfo.getText().toString());
//karan is name at position 4 in listview and i am checking it with name set in textview of next activity i.e infoActivity.
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
activity = null;
lv = null;
tvInfo = null;
contextInfoActivity = null;
}
希望这会对你有所帮助。我想问一些随意问的问题。谢谢