编写单元测试以检查服务是否已启动

3

我有一个以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或其他框架实现?

可能是重复的问题:如何检查 Android 中的服务是否正在运行?(https://dev59.com/LHRB5IYBdhLWcg3wgXhV) - Paul Burke
在SO上有很多这样的问题。你显然甚至没有花一点时间去做谷歌搜索。真丢人。 - Paul Burke
1
@PaulBurke,您可能没有仔细阅读问题。我问的是如何编写自动化测试以检查服务是否已启动。我认为这是不同的。此外,我看到“运行”和“已启动”/“意图启动服务已触发”之间存在差异。 - user468311
哇!我的错误,完全忽略了“单元测试”,只是认为您指的是“确定”方面的测试。请原谅我。取消踩。 - Paul Burke
SO不知道为什么不让我取消对某个问题的踩。告诉我除非编辑该问题,否则现在已被锁定。 :-( - Paul Burke
@PaulBurke 没问题。我也编辑了原始问题以澄清事情。 - user468311
2个回答

0

我不确定这是否符合您的要求,但这可能会有所帮助。

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;
}

正如您所看到的,您需要一个上下文变量。

另一种可能的方法是在您的服务中拥有一个静态布尔值,起始值为false,然后当您的IntentService启动时,将其更改为true

希望这可以帮助到您。


在编写测试时,你不应该触碰源代码。 - John Glen

0
虽然这是一个旧帖子,但我正在考虑回答这个问题以帮助某些人。
我使用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的设置,请参见此链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接