问题描述
我尝试为支持架构组件生命周期事件的功能添加单元测试.为了支持生命周期事件,我为函数添加了@OnLifecycleEvent
批注,该事件发生时我想做一些事情.
I tried to add a unit test for my function which supports architecture components lifecycle event. To support lifecycle event, I added the @OnLifecycleEvent
annotation for my function which I want to do something when that event occurred.
一切正常,但是我想为该功能创建一个单元测试,以检查发生预期事件时我的功能是否运行.
Everything is working as expected but I want to create a unit test for that function to check my function running when the intended event occurred.
public class CarServiceProvider implements LifecycleObserver {
public void bindToLifeCycle(LifecycleOwner lifecycleOwner) {
lifecycleOwner.getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onClear() {
Log.i("CarServiceProvider", "onClear called");
}
}
我尝试模拟LifecycleOwner并创建新的LifecycleRegistery来更改生命周期观察器的状态,但我没有这样做.
I tried to mock LifecycleOwner and create new LifecycleRegistery to change the state of lifecycle observer but I didn't do.
如何更改状态更改后调用的onClear()
函数?
How can I test my onClear()
function called when state changed ?
推荐答案
尽管我不是一个忠实的粉丝,但我还是会选择 Robolectric 利用 ActivityController 来实现.
Despite of I am not a big fan, I would go with Robolectric making use of ActivityController to achieve this.
鉴于观察者模式的可观察性"应用于以下事实Android Lifecycle工作流是活动",片段"……应用程序上下文是必须的,我们需要以某种方式将其引入我们的测试场景.
Given the fact that the "Observables" of the Observer pattern applied inAndroid Lifecycle workflow are Activities, Fragments... An application context is a must and we need somehow bring it to our test scenario.
我通过这样做达到了预期的结果
I achieved the expected result by doing this
build.gradle
testCompile "org.robolectric:robolectric:3.5.1"
CarServiceProviderTest.java
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class CarServiceProviderTest {
@Test
public void shouldFireOnClear(){
//Grab the Activity controller
ActivityController controller = Robolectric.buildActivity(JustTestActivity.class).create().start();
AppCompatActivity activity = (AppCompatActivity) controller.get();
//Instanciate our Observer
CarServiceProvider carServiceProvider = new CarServiceProvider();
carServiceProvider.bindToLifeCycle(activity);
//Fire the expected event
controller.stop();
//Assert
Assert.assertTrue(carServiceProvider.wasFired);
}
}
CarServiceProvider.java
public class CarServiceProvider implements LifecycleObserver {
public boolean wasFired;
public void bindToLifeCycle(LifecycleOwner lifecycleOwner) {
lifecycleOwner.getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onClear() {
wasFired = true;
}
}
这篇关于如何为Android体系结构组件生命周期事件添加单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!