Android Activity Scenario总结

Android Activity Scenario总结

Activity Scenario参考文档

概述

Activity Scenario是AndroidX提供的最新的跨平台测试框架。
它需要结合LifeCycle的State与Event使用。

启动

基本示例

与Robolectric比较

Before:
   MyActivity activity = Robolectric.setupActivity(MyActivity.class);
   assertThat(activity.getSomething()).isEqualTo("something");

 After:
   try(ActivityScenario scenario = ActivityScenario.launch(MyActivity.class)) {
     scenario.onActivity(activity -> {
       assertThat(activity.getSomething()).isEqualTo("something");
     });
   }

通过intent启动

允许通过intent来启动Activity,其中也允许携带参数。


控制状态

使Activity到不同的状态

 Before:
   ActivityController controller = Robolectric.buildActivity(MyActivity.class);
   controller.create().start().resume();  // Moves the activity state to State.RESUMED.
   controller.pause();    // Moves the activity state to State.STARTED. (ON_PAUSE is an event).
   controller.stop();     // Moves the activity state to State.CREATED. (ON_STOP is an event).
   controller.destroy();  // Moves the activity state to State.DESTROYED.

 After:
   try(ActivityScenario scenario = ActivityScenario.launch(MyActivity.class)) {
     scenario.moveToState(State.RESUMED);    // Moves the activity state to State.RESUMED.
     scenario.moveToState(State.STARTED);    // Moves the activity state to State.STARTED.
     scenario.moveToState(State.CREATED);    // Moves the activity state to State.CREATED.
     scenario.moveToState(State.DESTROYED);  // Moves the activity state to State.DESTROYED.
   }

LifeCycle

image.png

使Activity到更多状态

根据前面的Lifecycle示意图,会发现State并没有PAUSED,STOPED状态。如何实现Activity到达该状态呢。如下所示:

   try(ActivityScenario scenario = ActivityScenario.launch(MyActivity.class)) {
     scenario.moveToState(State.CREATED);    // Moves the activity state to State.CREATED.
     scenario.moveToState(State.STARTED);    // Moves the activity state to State.STARTED.
     scenario.moveToState(State.RESUMED);    // Moves the activity state to State.RESUMED.

     // 当对已经处于RESUMED状态的Activity,让其回到STARTED状态时,即相当于执行了onPause()方法。
     scenario.moveToState(State.STARTED);    // 使得Activity回到Started状态,并执行onPause.

     // 同理,要执行onStop,则
    scenario.moveToState(State.CREATED);    // Moves the activity state to State.CREATED. 并且执行了onStop()方法。
   }

根据上面的例子发现,若要执行Activity中的生命周期方法,是通过在不同State中转移而实现的。没有PAUSED,STOPPED对应状态,只有对应的事件。

执行行为与验证行为

通过onActivity可以在Activity的主线程中执行行为,并验证行为

关闭Scenario

测试用例执行完毕,Activity依然保持在某个状态运行,故建议在测试用例执行完毕,调用

scenario.close()

你可能感兴趣的:(Android Activity Scenario总结)