【发布时间】:2015-11-08 02:00:59
【问题描述】:
是否可以在 robolectric 的帮助下对 GCM 上游消息进行单元测试?这是我的单位:
public void sendUpstream(Bundle data)
{
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String id = "trv2" + System.currentTimeMillis();
try {
gcm.send(GCM_SENDER_ID + "@gcm.googleapis.com", id, data);
} catch (IOException e) {
printStackTrace(e);
}
}
尝试使用 robolectric 对其进行测试会产生以下堆栈跟踪:
java.lang.NullPointerException
at com.google.android.gms.gcm.GoogleCloudMessaging.zza(Unknown Source)
at com.google.android.gms.gcm.GoogleCloudMessaging.send(Unknown Source)
at com.google.android.gms.gcm.GoogleCloudMessaging.send(Unknown Source)
这似乎告诉我,robolectric 没有使用影子类,而是直接尝试使用 GoogleCloudMessaging 类并失败,因为测试没有在设备上执行。
我尝试创建一个影子 GoogleCloudMessaging 类,看看是否可行。这是影子:
@Implements(GoogleCloudMessaging.class)
public class ShadowGCM {
Bundle data;
String to;
String msgId;
public ShadowGCM() {}
@Implementation
public void send(String to, String msgId, Bundle data) {
this.data = data;
this.to = to;
this.msgId = msgId;
}
}
以下注释已添加到我的测试类中以使其正常工作。
@RunWith(MyTestRunner.class)
@Config(manifest = "src/main/AndroidManifest.xml", shadows = {ShadowGCM.class } ,
constants = BuildConfig.class, sdk = Build.VERSION_CODES.KITKAT)
MyTestRunner 是我创建的自定义测试运行器,因为仅将“shadows”属性放入配置注释似乎不起作用。这是测试运行器。
public class MyTestRunner extends RobolectricGradleTestRunner {
public MyTestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
public InstrumentationConfiguration createClassLoaderConfig() {
InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
builder.addInstrumentedClass(ShadowGCM.class.getName());
builder.addInstrumentedClass(ShadowInstanceID.class.getName());
return builder.build();
}
}
但在所有这些工作之后。 NullPointerException 仍然存在。 Roboelectric 看起来不像是在使用我的影子课程。
【问题讨论】:
-
请注意,最新的 Robolectric 不再需要自定义跑步者。
标签: android google-cloud-messaging robolectric android-testing