1、添加环境(Android Studio2.3+)
// robolectrictestCompile '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();
}
说明:接收广播消息类就不再阐述。
推荐博文: