【问题标题】:Writing a unit test to check if a Service has started编写单元测试以检查服务是否已启动
【发布时间】:2014-09-22 10:26:07
【问题描述】:

我有一门从IntentService开始的课程:

public class MyClass(){
    public void doStuff(){
       Intent intent = new Intent(context, MyService.class);
       intent.putExtra(KEY, stringExtra);
       context.startService(intent);
    }
}

现在我想单元测试 MyClass。我想检查启动我的服务的意图是否被触发以及它是否具有正确的附加功能。像这样的:

public void testServiceStarted(){
    MyClass myClass = new MyClass();
    myClass.doStuff();

    // Assert MyService was stated and received arguments
}

这可以通过 Instrumentation 或其他框架实现吗?

【问题讨论】:

  • 关于 SO 的问题有很多。您显然甚至没有花一点时间进行 Google 搜索。耻辱。
  • @PaulBurke 你可能没有仔细阅读这个问题。我问如何编写一个检查服务是否启动的自动化测试。我认为这是不同的。我还看到“正在运行”和“已启动”/“启动服务的意图被触发”之间的区别。
  • 哇!我的错误,完全错过了“单元测试”,只是认为你的意思是测试,就像“确定”一样。请原谅。删除反对票。
  • SO 不让我出于某种原因撤消否决票。告诉我它现在被锁定,除非问题被编辑。 :-(

标签: android unit-testing testing junit


【解决方案1】:

我不知道这是否是您正在寻找的,但这可能有用。

private boolean isMyServiceRunning(Class<?> serviceClass,Context context) {
    ActivityManager manager = (ActivityManager)context. getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(MySercice.service.getClassName())) {
            Log.i("Service already","running");
            return true;
        }
    }
    Log.i("Service not","running");
    return false;
}

如您所见,您将需要一个 Context 变量。

另一种可能的方法是在您的服务中添加一个静态布尔值,以 false 开头,然后当您的 IntentService 启动时,将其更改为 true

希望对你有帮助

【讨论】:

    【解决方案2】:

    虽然这是一篇旧帖子,但我正在考虑回答这个可能对某人有所帮助的问题。

    我使用 Roboelectric 编写此类单元测试,您可以通过以下方式检查服务是否以正确的操作或意图启动。

    @Config(constants = BuildConfig.class)
    @RunWith(RobolectricTestRunner.class)
    public class MyServiceTest {
    
        @Test
        public void testMyServiceStartedWithRightActionAndIntent() {
    
            final Intent realIntent = ShadowApplication.getInstance().getNextStartedService();
    
            // Test if the service intent is not null
            Assert.assertNotNull("Obtained the my service intent", realIntent);
    
            // Test if the service intent has any extra with the maching name with MY_EXTRA
            Assert.assertTrue("My service does not have the right extra", realIntent.hasExtra(MY_EXTRA));
    
            // Test if the service has the right action.
            Assert.assertEquals("My Service does not have right action", realIntent.getAction(), SERVICE_ACTION);
        }
    }
    

    如需 Roboelectric 设置,请see this link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2012-02-17
      • 2014-02-24
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多