是否有可能在robolectric的帮助下对GCM上行消息进行单元测试?这是我的单位:Robolectric和GoogleCloudMessaging
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是我创建,因为只把“阴影”属性到配置注释似乎没有工作的自定义测试运行。这里是测试跑步者。
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不再需要自定义运行程序。 – Gabor