Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen Android ActivityTestRule's beforeActivityLaunched method in an android test

How do I listen ActivityTestRule's beforeActivityLaunched() method in an android test.

My workaround is creating a custom ActivityTestRule and providing a callback on constructor. Is it a bad practice? Same way is it OK to listen for ActivityTestRule constructor method.

Here is my code:

public class CustomActivityTestRule<A extends Activity> extends ActivityTestRule<A> {

    public interface onBeforeListener{
        void onBefore(String message);
    }

    private onBeforeListener listener;

    public CustomActivityTestRule(Class<A> activityClass, onBeforeListener listener) {
        super(activityClass);
    }

    @Override
    protected void beforeActivityLaunched() {
        super.beforeActivityLaunched();
        listener.onBefore("before activity launch");
    }
}

In android test class, I can do something like:

@Rule public CustomActivityTestRule<MainActivity> mainActivityActivityTestRule = new
            CustomActivityTestRule<MainActivity>(MainActivity.class, new CustomActivityTestRule.onBeforeListener() {
        @Override
        public void onBefore(String message) {
            //do something before activity starts
        }
    });

Same way it is able to do something on junit rule instantiating. Is there any other way to listen for junit test rule instantiating?

like image 409
Ruwanka Madhushan Avatar asked May 08 '16 15:05

Ruwanka Madhushan


1 Answers

You can override beforeActivityLaunched without creation of a new class.

I'm using the following in my tests:

@Rule
public ActivityTestRule<MainActivity> mainActivityActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class) {

    @Override
    protected void beforeActivityLaunched() {
        super.beforeActivityLaunched();
    }

};
like image 146
Artem Mostyaev Avatar answered Nov 15 '22 14:11

Artem Mostyaev