【问题标题】:is there a way to test a public method in an Android Service?有没有办法在 Android 服务中测试公共方法?
【发布时间】:2013-11-23 21:13:38
【问题描述】:

我有一个服务可以监听 GCM 消息并解析 JSON。最终(取决于消息内容)它会写入 SharedPreferences,因此它需要getApplicationContext()

如果我“作为常规对象”对服务进行测试(创建服务,然后执行该方法),getApplicationContext() 在运行测试时以 null 结束

如果我使用 ServiceTestCase

    public void testHandleAuth() {

               // MyClass is tested
               Intent intent=new Intent("com.duniap.ptp.GcmIntentService");
               this.startService(intent);
               GcmIntentService tester = new GcmIntentService();
               // a dummy json encoded in base64
               dummyAuth64="eyJkZXZpY2UiOnsiaWQiOjU2LCJzZWNyZXQiOiJGc3VCcWZsdVFcL2l5bit5TlZadW5uZz09In0sImFjdGlvbiI6ImF1dGhvcml6ZSJ9";
               byte[] bytes = Base64.decode(dummyAuth64, Base64.DEFAULT);
               String dummyAuth = new String(bytes);
               tester.handleGCMmessage(dummyAuth);
                   //null pointer, if I debug I trace it to getApplicationContext() within this method

    }

我仍然得到同样的空异常

【问题讨论】:

  • 你在哪里使用Context

标签: java android testing junit


【解决方案1】:

处理此类情况的常用方法是使用模拟框架,您可以在其中有效地模拟您的被测方法与之交互的上下文。因此,您可以模拟 getApplicationContext() 以返回足以与 SharedContext 一起使用的模拟上下文对象。

一般参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多