在Android Studio中使用Robolectric进行Android测试问题

3
首先,我想声明我对Android中缺乏适当的测试基础设施感到沮丧...或者也许是我太笨了,我不知道...
最终,我成功地设置了android-test-plugin,并为一个包含一个CustomMapFragment的活动编写了几个测试用例。这个CustomMapFragment是我编写的一个类,它扩展了SupportMapFragment
所有尝试使用下面代码获取此活动实例的测试都通过了:
activity = Robolectric.buildActivity(MyActivity.class).create().get();

出现错误:

java.lang.NoClassDefFoundError: com/google/android/gms/maps/GoogleMap$OnInfoWindowClickListener

在活动的setContentView方法中。

该活动的xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MyActivity">

    <fragment
            android:id="@+id/customMapFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            class="com.myproject.CustomMapFragment"/>
</RelativeLayout>

有没有解决此问题的方法? 非常感谢您的帮助。

1
我理解你的沮丧。我也遇到了同样的问题,但是由于Robolectric在加载类时出现了NoClassDefFoundError错误,所以我无法运行任何测试,即使是assertTrue(true)测试也会失败。这是我的问题,其中包含我遇到的错误信息:http://stackoverflow.com/questions/18434217/robolectric-fails-to-run-tests-with-google-play-services-maps - alex
我认为这是一个常见问题,与地图没有直接关联,因为我在使用 Google 云消息传递的一些类时也遇到了相同的错误。很高兴知道有人能理解你 :) 如果有人在这里回答,我会告诉你的。 - Thomas Kaliakos
你是如何添加 Google Play 服务依赖的?使用 Google 存储库还是其他方式? - alex
1个回答

2

我有一个临时解决方案。问题似乎是android-test-plugin无法读取aar文件。我的解决方案是将依赖项添加到jar文件,而不仅仅是testCompile,如下所示:

testCompile files('YOUR_ANDROID_SDK_FOLDER/extras/google/google_play_services/libproject/google-play-services_lib/libs/google-play-services.jar')

像这样,我能够运行一个简单的测试,例如创建一个LatLng并检查它是否不为空,没有错误。希望有所帮助。
编辑
由于Github上的SuperJugy提供了更好的解决方案,建议应用此提交中的修复:https://github.com/SuperJugy/gradle-android-test-plugin/commit/d5b7836cf7278dc9d0fe765b635de60c33911d72

一旦我有时间测试这个,我会接受你的答案。不管怎样,非常感谢 @alex。 - Thomas Kaliakos
好吧,我放弃了...我实际上成功克服了这些“NoClassDefFoundErrors”,但现在我得到了“java.lang.RuntimeException: Stub!”好像在android.jar之前将Robolectric添加到类路径中。无论如何,构建android-test-plugin的最新版本似乎已经解决了以前的问题,因此我将接受您的答案。谢谢。 - Thomas Kaliakos
嗯,我也在不断地解决问题,我实际上已经放弃编写测试了。由于样式问题,我不得不使用Robolectric的快照版本,但这个版本找不到资源文件... - alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接