【问题标题】:Robolectric and GoogleCloudMessagingRobolectric 和 GoogleCloudMessaging
【发布时间】: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


【解决方案1】:

小错误...builder.addInstrumentedClass( .. ); 行指定了一个可以被遮蔽的类。此时不要使用 ShadowGCM,而是使用 GoogleCloudMessaging。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多