我有多个按钮,这些按钮是在for循环中动态创建的,并且没有ID。我需要对这些按钮进行自动化测试。我怎么能用Espresso做到这一点?这是创建各种按钮的for循环:
for (int i = 0; i < numberOfSamples; i++) {
TableRow.LayoutParams vl = new TableRow.LayoutParams(30,30);
Button b = new Button(context);
b.setId(((blockNumber * 10000)+i));
//b.setHint(i);
//b.setHint(blockNumber);
// double selectedGrade = 0;
// if(FinalSurvey.multi[blockNumber][i] != 0){
// selectedGrade = FinalSurvey.multi[blockNumber][i];
// }
// final int makeHighlight = selectedGrade;
b.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.a));
b.setAlpha(1.0f);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewsAdding va = new ViewsAdding();
va.showGrades(context, v, grades);
view = v;
maincontext = context;
}
});
if(i%5 == 0){
innerLayout = new LinearLayout(context);
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
innerLayout.setLayoutParams(innerparams);
vl.setMargins(5, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
if(i == numberOfSamples-1){
mainLinearLayout.addView(innerLayout);
}
b = null;
}else if (i%5 ==1) {
vl.setMargins(22, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
if(i == numberOfSamples-1){
mainLinearLayout.addView(innerLayout);
}
b = null;
}else if (i%5 ==2) {
vl.setMargins(25, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
mainLinearLayout.addView(innerLayout);
b = null;
}else if (i%5 ==3) {
innerLayout = new LinearLayout(context);
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
innerLayout.setLayoutParams(innerparams);
vl.setMargins(35, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
if(i == numberOfSamples-1){
mainLinearLayout.addView(innerLayout);
}
b = null;
}else{
vl.setMargins(30, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
mainLinearLayout.addView(innerLayout);
b = null;
}
}
return mainLinearLayout;
}
答案 0 :(得分:4)
在您创建按钮的代码中,根据具体情况为按钮添加标签:
button.setTag("someTag");
所以在你的情况下,你可以在你的if子句中做到:
if(i%5 == 0){
...
b.setTag("case0-" + i);
...
}else if (i%5 ==1) {
...
b.setTag("case1-" + i);
...
}
...
然后在您的测试中,您可以使用此按钮获取或单击它:
onView(allOf(withTagValue(is((Object) "case0-0")), isDisplayed())).perform(click());
onView(allOf(withTagValue(is((Object) "case0-0")), isDisplayed())).perform(click());
您也可以用循环替换“case0-0”字符串以重新生成标记