簡體   English   中英

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)

這似乎告訴我,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看起來不像在使用我的影子類。

小錯誤... line builder.addInstrumentedClass( .. ); 指定一個可能被遮蓋的類。 此時,請使用GoogleCloudMessaging而不是ShadowGCM。

manifest = "src/main/AndroidManifest.xml"可能會在以后給您帶來麻煩。 相反,您應該從RobolectricGradleTestRunner已經完成的構建目錄中獲取清單。 如果您在AndroidStudio中遇到問題,請閱讀http://robolectric.org/getting-started/上的 “ Linux和Mac用戶注意事項”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM