3

我正在使用 ServiceTestCase 为服务编写单元测试。

该服务基本上执行一个 AsyncTask,它做一些工作,然后在 onPostExecute() 中做一些其他事情。

当我在(虚拟)设备中运行和调试它时,该服务按预期工作。

但是在扩展 ServiceTestCase 的测试中,我只进入了 doInBackground()。一旦方法返回, onPostExecute() 就永远不会被调用。我让测试 sleep() 所以 AsyncTask 有时间完成它的工作。

这是简化的服务:

public class ServiceToTest extends Service {
    private AtomicBoolean busy = new AtomicBoolean(false);

    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, final int flags,
        final int startId) {
        this.handleCommand();
        return START_NOT_STICKY;
    }

    /**
    * Workaround for http://code.google.com/p/android/issues/detail?id=12117
    */
    @Override
    public void onStart(final Intent intent, final int startId) {
        this.handleCommand();
    }

    public void handleCommand() {
        new TaskToTest().execute();
    }

    public boolean isBusy() {
        return busy.get();
    }

    private class TaskToTest extends AsyncTask<Boolean, Void, TestInfo> {
        @Override
        protected void onPreExecute() {
            busy.set(true);
        }

        @Override
        protected TestInfo doInBackground(final Boolean... args) {
            return null;
        }

        @Override
        protected void onPostExecute(final TestInfo info) {
            busy.set(false);
        }
    }
}

这是对它的测试:

public class ServiceTest extends ServiceTestCase<ServiceToTest> {
    public ServiceTest() {
        super(ServiceToTest.class);
    }

    public void testIsBusy() throws InterruptedException {
        startService(new Intent("this.is.the.ServiceToTest"));  
        ServiceToTest serviceToTest = this.getService();
        assertTrue(serviceToTest.isBusy());
        Thread.sleep(10000);
        assertFalse(serviceToTest.isBusy());
    }
}

我想 ServiceTestCase 提供的环境有些有限,所以这不起作用,但是我能做些什么让它工作吗?

干杯,托斯滕

4

4 回答 4

1

问题是您的后台线程正在等待 UI 处于“活动状态”,您需要调用Looper.prepare()and Looper.loop()。在此页面中对此进行了更好的解释。

于 2011-05-20T02:37:57.073 回答
1

所以只是为了跟进我是如何让它与 dmon 提供的信息一起工作的。

我将测试更改为以下内容:

public class ServiceTest extends ServiceTestCase {

public ServiceTest() {
    super(ServiceToTest.class);
}

public void testIsBusy() throws InterruptedException {

    // Starts the service and asserts that onPreExecute() was called
    ServiceTestThread serviceTestThread = new ServiceTestThread();
    serviceTestThread.start();

    // Wait for the service to start and complete doInBackground()
    // TODO Implement something smarter than this...
    Thread.sleep(1000);

    // Assert that onPostExecute() was called
    assertFalse(serviceTestThread.serviceToTest.isBusy());

}

private class ServiceTestThread extends Thread {

    ServiceToTest serviceToTest;

    public void run() {
        Looper.prepare();

        startService(new Intent("this.is.the.ServiceToTest"));

        serviceToTest = getService();

        assertTrue(serviceToTest.isBusy());

        Looper.loop();
    }

}

}

我现在将看到使这个 ServiceTestThread 更通用,以便它可以被重用。

托尔斯滕

于 2011-05-20T12:04:54.790 回答
0

不确定这对其他人是否有用,但这是我尝试抽象 Tortens 答案并使其更可重用的尝试。

    private synchronized boolean getWaitFlag()
    {
        return _waitFlag;
    }

    private boolean _waitFlag;

    private synchronized void setWaitFlag(boolean value)
    {
        _waitFlag = value;
    }

    private void waitForCompletionFlag() throws InterruptedException
    {
        Calendar cal = Calendar.getInstance();
        while (getWaitFlag() == false)
        {
            Thread.sleep(10);
            if (Calendar.getInstance().getTimeInMillis() - cal.getTimeInMillis() > 1000) // Wait at most 1 second
            {
                Log.e("timeout", "timed out waiting to complete task");
                break;
            }
        }
    }

private abstract class EmulatedUI extends Thread
    {
        public abstract void doWork();

        public void run()
        {
            Looper.prepare();
            doWork();
            Looper.loop();
        }
    }

public void testSomething() throws InterruptedException
{
    EmulatedUI thread = new EmulatedUI() {

        @Override
        public void doWork()
        {
            _objectToTest.someAsyncCall(new WorkCompletedCallback() {

                        @Override
                        public void onComplete()
                        {
                                   // could possibly assert things here
                            setWaitFlag(true);
                        }
                    });

        }
    };
    thread.start();
    waitForCompletionFlag();
    // assert things here since you know the async task has completed.
}
于 2012-06-08T22:46:18.517 回答
0

尝试从测试运行程序线程而不是 ui 线程绑定到服务时,我遇到了同样的问题。尝试从 ui 线程调用 startService。

public void testIsBusy() throws Exception {
  final CountDownLatch latch = new CountDownLatch(1);

  new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
      startService(new Intent("this.is.the.ServiceToTest"));  
      ServiceToTest serviceToTest = this.getService();
      assertTrue(serviceToTest.isBusy());
      Thread.sleep(10000);
      assertFalse(serviceToTest.isBusy());
      latch.countDown();
    }
  });

  latch.await(5, TimeUnit.SECONDS);
}
于 2013-12-03T08:31:21.297 回答