如何在 Espresso 测试中调用自定义视图的方法?
How to call a method on a custom view in an Espresso test?
我有一个自定义视图,我需要在该视图上调用特定方法来打开 activity。在 Espresso 测试中执行此操作的正确方法是什么?
我只需要扩充此视图还是需要编写自定义 ViewAction
?
您可以像这样创建自定义 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());
为了在断言中使用自定义方法的结果,我对 lellomans answer 进行了以下修改:
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();
}
}
我没有创建新的 MyCustomViewAction(),而是创建了一个 myAction 对象供以后重用。
MyCustomViewAction myAction = new MyCustomViewAction();
onView(withId(whatever)).perform(myAction);
MyReturnObject returnValueForSpecialAssertions = myAction.returnValue;
// assert something with returnValueForSpecialAssertions
我有一个自定义视图,我需要在该视图上调用特定方法来打开 activity。在 Espresso 测试中执行此操作的正确方法是什么?
我只需要扩充此视图还是需要编写自定义 ViewAction
?
您可以像这样创建自定义 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());
为了在断言中使用自定义方法的结果,我对 lellomans answer 进行了以下修改:
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();
}
}
我没有创建新的 MyCustomViewAction(),而是创建了一个 myAction 对象供以后重用。
MyCustomViewAction myAction = new MyCustomViewAction();
onView(withId(whatever)).perform(myAction);
MyReturnObject returnValueForSpecialAssertions = myAction.returnValue;
// assert something with returnValueForSpecialAssertions