I have a custom view on which I need to call a specific method to open an activity. What is the right way to do this in an Espresso test?
Do I just need to inflate this view or do I need to write a custom ViewAction
?
you can create a custom ViewAction like this
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
}
}
and use it as you normally would, like
onView(withId(whatever)).perform(new MyCustomViewAction());
In order to use the result of a custom method in assertions, I came up with the following modification of 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();
}
}
and instead of creating a new MyCustomViewAction(), I created a myAction object for later reuse.
MyCustomViewAction myAction = new MyCustomViewAction();
onView(withId(whatever)).perform(myAction);
MyReturnObject returnValueForSpecialAssertions = myAction.returnValue;
// assert something with returnValueForSpecialAssertions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With