2

是否有可能在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看起来不像是在用我的影子课。

+0

请注意,最新的Robolectric不再需要自定义运行程序。 – Gabor

回答

3

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

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

+0

你是espress的专家吗?那么请看看你是否知道这一个http://stackoverflow.com/questions/33662404/espresso-webview-select-hidden-element谢谢 – middlestump