教程网上比较多,但是因为最新版是3.0了,所以用上面的官网robolectric资料还是比较好,配置比较简单,基本是在gradle里加上依赖,再在build variants里把artifact改为junit就可以开始写擦了。
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.0"
本来打算要做项目中使用,中间了遇到了几个问题,当然如果你只是用官方的demo去实验,好像一切都很完美。
试过demo,我也是觉得这个框架很强大,运行很快,不需要连接手机,但是我接入之前写的一个app时就遇到问题了,首先遇到一个warn加exception
WARNING: No manifest file found at ./AndroidManifest.xml.Falling back to the Android OS resources only.
To remove this warning, annotate your test class with @Config(manifest=Config.NONE).
android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f03001b
at org.robolectric.shadows.ShadowResources.checkResName(ShadowResources.java:343)
at org.robolectric.shadows.ShadowResources.resolveResName(ShadowResources.java:338)
at org.robolectric.shadows.ShadowResources.loadXmlResourceParser(ShadowResources.java:429)
at android.content.res.Resources.loadXmlResourceParser(Resources.java)
这个可以通过在Config里配置manifest路径解决。
然后是初始化时自定义的application里异常,因为我在application里进行了一些初始化,比如sd卡目录什么的,导致直接运行失败,后来用框架提供的shadow,然后在Config里配置application为自定义的就可以了。
@Implements(AssistApplication.class)
public class ShadowApplication extends Application{
@Implementation
public static void initDownloader(){}
}
之后想测试一下toast测试
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class,
manifest = "src/main/AndroidManifest.xml",
application = ShadowApplication.class,
shadows = {ShadowApplication.class},
sdk = 19)
public class AssistActivityTest {
@Before
public void setUp(){
}
@Test
public void testAssist(){
ProxyActivity activity = Robolectric.setupActivity(ProxyActivity.class);
View view = activity.findViewById(R.id.id_layout_proxy_switch);
view.performClick();
ShadowLooper.idleMainLooper();
assertEquals(ShadowToast.getLatestToast(),"请设置ip地址");
}
}
遇到了如下异常,去github上看了[issues](https://github.com/robolectric/robolectric/labels/defect?page=2&q=is%3Aopen+label%3Adefect)还是有很多问题没解决,所以暂时还是打算不在项目中使用了。
java.lang.NullPointerException
at org.robolectric.shadows.ShadowAssetManager$OverlayedStyle.equals(ShadowAssetManager.java:318)
at org.robolectric.shadows.ShadowAssetManager.applyThemeStyle(ShadowAssetManager.java:291)
at org.robolectric.shadows.ShadowResources$ShadowTheme.applyStyle(ShadowResources.java:461)
at android.content.res.Resources$Theme.applyStyle(Resources.java)
at android.view.ContextThemeWrapper.onApplyThemeResource(ContextThemeWrapper.java:132)
at android.app.Activity.onApplyThemeResource(Activity.java:3360)
at android.view.ContextThemeWrapper.initializeTheme(ContextThemeWrapper.java:144)
at android.view.ContextThemeWrapper.setTheme(ContextThemeWrapper.java:89)
at org.robolectric.shadows.ShadowActivity.setThemeFromManifest(ShadowActivity.java:85)
at org.robolectric.shadows.CoreShadowsAdapter$1.setThemeFromManifest(CoreShadowsAdapter.java:35)
at org.robolectric.util.ActivityController.attach(ActivityController.java:58)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:121)