Android provides a testing framework for Service objects that can run them in
isolation and provides mock objects. The test case class for Service objects is
This document describes techniques for testing Service objects. If you aren't familiar with the
Service class, please read the Services document. If you aren't familiar with Android testing, please read
Testing Fundamentals,
the introduction to the Android testing and instrumentation framework.
Service Design and Testing
When you design a Service, you should consider how your tests can examine the various states
of the Service lifecycle. If the lifecycle methods that start up your Service, such as
Most other testing is facilitated by the methods in the
ServiceTestCase
Notice that the parameters to ServiceTestCase.bindService()are different from
those for Service.bindService(). For the ServiceTestCase version,
you only provide an Intent. Instead of returning a boolean,
ServiceTestCase.bindService() returns an object that subclasses
The super.setUp() as the first statement in the override.
The methods Mock object classes.
By default,
Mock object classes
ServiceTestCase assumes that you will use a mock Context or mock Application
(or both) for the test environment. These objects isolate the test environment from the
rest of the system. If you don't provide your own instances of these objects before you
start the Service, then
To inject a mock Application object into the Service under test, first create a subclass of
MockApplication is a subclass of
You inject a mock Context into the Service under test with the
Testing Fundamentals.
需要测试什么?
The topic 需要测试什么?
lists general considerations for testing Android components.
Here are some specific guidelines for testing a Service:
Test that your Service correctly handles multiple calls from
Context.startService(). Only the first call triggers
Service.onCreate(), but all calls trigger a call to
Service.onStartCommand().
In addition, remember that startService() calls don't
nest, so a single call to Context.stopService() or
Service.stopSelf() (but not stopSelf(int))
will stop the Service. You should test that your Service stops at the correct point.
Test any business logic that your Service implements. Business logic includes checking for
invalid values, financial and arithmetic calculations, and so forth.