Customizing the Test Runner

There are several situations where you want to customize Robolectric's test runner to perform some operation before all tests are run, or even before each test method is run. One good example is initializing a dependency injection framework with a different set of dependencies for your test. Fortunately, Robolectric has a way to hook into the test lifecycle. If you define an Application class in your AndroidManifest.xml, Robolectric will automatically try and load a test version of your application class first. For example:

Let's say you've defined a FooApplication in your manifest:

<application android:name=".FooApplication">

If you're using RoboGuice, you would initialize the injector in your Application class:

public class FooApplication extends Application { @Override public void onCreate() { super.onCreate(); ApplicationModule module = new ApplicationModule(); setBaseApplicationInjector(this, DEFAULT_STAGE, newDefaultRoboModule(this), module); } } 

You can define a test version of the application named TestFooApplication:

public class TestFooApplication extends FooApplication implements TestLifecycleApplication { @Override public void onCreate() { super.onCreate(); TestApplicationModule module = new TestApplicationModule(); setBaseApplicationInjector(this, DEFAULT_STAGE, newDefaultRoboModule(this), module); } @Override public void beforeTest(Method method) { } @Override public void prepareTest(Object test) { getInjector(this).injectMembers(test); } @Override public void afterTest(Method method) { } } 

Robolectric will load the test version of the application which you can use to load a different set of bindings during tests.

转载于:https://www.cnblogs.com/yexiant/p/5692850.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值