Robolectric 和 GoogleCloudMessaging

Robolectric and GoogleCloudMessaging

是否可以在 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)

这似乎告诉我,不是使用影子 class robolectric 而是直接尝试使用 GoogleCloudMessaging class 并失败,因为测试不是在设备上执行。

我尝试创建影子 GoogleCloudMessaging class 看看是否可行。这是影子:

@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;
    }
}

以下注释已添加到我的测试中 class 以使其正常运行。

@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 看起来不像是在使用我的影子class。

小错误...行 builder.addInstrumentedClass( .. ); 指定了一个 class 可以隐藏。此时使用 GoogleCloudMessaging 而不是 ShadowGCM。

manifest = "src/main/AndroidManifest.xml"部分以后可能会给您带来麻烦。相反,您应该从 RobolectricGradleTestRunner 已经完成的构建目录中获取清单。如果您在 AndroidStudio 中遇到问题,请阅读 http://robolectric.org/getting-started/

中的 "Note for Linux and Mac Users"