是否可以借助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看起来不像在使用我的影子类。
小错误...该行builder.addInstrumentedClass( .. );
指定了可能被遮盖的类。此时,请使用GoogleCloudMessaging而不是ShadowGCM。
该部分manifest = "src/main/AndroidManifest.xml"
可能会在以后给您带来麻烦。相反,您应该从RobolectricGradleTestRunner已经完成的构建目录中获取清单。如果您在AndroidStudio中遇到问题,请阅读http://robolectric.org/getting-started/上的“ Linux和Mac用户注意事项”
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句