我有一个自定义视图,我需要调用一个特定的方法来打开一个活动。在浓缩咖啡测试中,这样做的正确方法是什么? 我只需要膨胀这个视图,或者我需要编写一个自定义的ViewAction?
答案 0 :(得分:10)
您可以像这样创建自定义ViewAction
public class MyCustomViewAction implements ViewAction{
@Override
public Matcher<View> getConstraints(){
return isAssignableFrom(YourCustomView.class);
}
@Override
public String getDescription(){
return "whatever";
}
@Override
public void perform(UiController uiController, View view){
YourCustomView yourCustomView = (YourCustomView) view;
yourCustomView.yourCustomMethod();
// tadaaa
}
}
并像往常一样使用它,例如
onView(withId(whatever)).perform(new MyCustomViewAction());
答案 1 :(得分:0)
为了在断言中使用自定义方法的结果,我提出了对lellomans答案的以下修改:
public class MyCustomViewAction implements ViewAction{
MyReturnObject returnValue = null;
@Override
public Matcher<View> getConstraints(){
return isAssignableFrom(YourCustomView.class);
}
@Override
public String getDescription(){
return "whatever";
}
@Override
public void perform(UiController uiController, View view){
YourCustomView yourCustomView = (YourCustomView) view;
// store the returnValue
returnValue = yourCustomView.yourCustomMethod();
}
}
我创建了一个myAction对象供以后重用,而不是创建一个新的MyCustomViewAction()。
MyCustomViewAction myAction = new MyCustomViewAction();
onView(withId(whatever)).perform(myAction);
MyReturnObject returnValueForSpecialAssertions = myAction.returnValue;
// assert something with returnValueForSpecialAssertions