Android单元测试之 Robolectric3.0+

1、添加环境(Android Studio2.3+)

// robolectric
testCompile 'org.robolectric:robolectric:3.3'
testCompile "org.robolectric:robolectric-annotations:3.3"
testCompile 'com.google.inject:guice:3.0'
//robolectric针对support-v4的shadows
testCompile "org.robolectric:shadows-support-v4:3.1.4"

2、javaTest添加代码(不是androidTest)

@RunWith(MyRobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, packageName = "com.xxx.xxxservice")
public class XXXServiceTest {
 

}

3、云端Maven项目对象模型

public class MyRobolectricTestRunner extends RobolectricTestRunner {
    public MyRobolectricTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
        // 从源码知道MavenDependencyResolver默认以RoboSettings的repositoryUrl和repositoryId为默认值,因此只需要对RoboSetting进行赋值即可
        RoboSettings.setMavenRepositoryId("alimaven");
        RoboSettings.setMavenRepositoryUrl("http://maven.aliyun.com/nexus/content/groups/public/");
    }
}

4、测试广播为例

@Test
public void onDetected(){

String action = PEOPLE_INFO_BROADCAST;
Intent intent = new Intent(action);
intent.putExtra("BroadcastTest", "test");
//测试是否注册广播接收者
assertTrue(shadowApplication.hasReceiverForIntent(intent));
//以下测试广播接受者的处理逻辑是否正确
myReceiver.onReceive(RuntimeEnvironment.application,intent);
String info = intent.getExtras().getString("BroadcastTest");
assertEquals( "test", info);
MyReceiver myReceiver = new MyReceiver();

}

说明:接收广播消息类就不再阐述。

推荐博文:

Android单元测试框架Robolectric3.0介



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值