Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method on a custom view in an Espresso test?

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?

like image 781
Vadims Savjolovs Avatar asked Aug 30 '16 14:08

Vadims Savjolovs


2 Answers

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());
like image 182
lelloman Avatar answered Oct 16 '22 17:10

lelloman


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
like image 1
Aldinjo Avatar answered Oct 16 '22 16:10

Aldinjo