I want to test a Service with my Application class pre-instantiated, a
bit like what happens on a real device.

My problem is I can't figure out a way to do this with the correct
Application context AND having the Application being instantiated
EXACTLY once.  Being instantiated multiple times causes issues if
there is code which uses singletons, and/or performs registrations
tasks that should only be performed once.

Full code for this snippet can be downloaded here:
http://www.zedray.co.uk/temp/ServiceSnippet.zip

My test code:
=============================
public class ServiceDemoTest extends ServiceTestCase<ServiceDemo> {
  protected final void setUp() throws Exception {
        /** Setup the MainApplication. **/
        mApplication = (ApplicationDemo)
Instrumentation.newApplication(ApplicationDemo.class, getContext());
        mApplication.onCreate();
        setApplication(mApplication);

        super.setUp();
    }

    @Override
    protected final void tearDown() throws Exception {
        if (mApplication != null) {
            mApplication.onTerminate();
            mApplication = null;
        }
        setApplication(null);

        super.tearDown();
    }

    @MediumTest
    public final void testStartable() {
        startService(new Intent(getContext(), ServiceDemo.class));
    }
=============================

This produces the following trace, which suggests that several
instances of my Application are being created, or just that onCreate()
is being called several times:

=============================
05-21 16:20:43.667: INFO/ServiceSnippet(4126):
ApplicationDemo.onCreate() mInstanceId[0]
05-21 16:20:46.398: INFO/ServiceSnippet(4143):
ApplicationDemo.onCreate() mInstanceId[0]
05-21 16:20:46.437: INFO/ServiceSnippet(4143):
ApplicationDemo.onCreate() mInstanceId[1]
05-21 16:20:46.447: INFO/ServiceSnippet(4143): ServiceDemo.onCreate()
05-21 16:20:46.447: INFO/ServiceSnippet(4143): ServiceDemo.onStart()
05-21 16:20:46.466: INFO/ServiceSnippet(4143):
ApplicationDemo.onCreate() mInstanceId[2]
05-21 16:20:46.488: INFO/ServiceSnippet(4143):
ApplicationDemo.onCreate() mInstanceId[3]
=============================

I have no idea why the onCreate() keeps getting called, and how to
ensure it only happens once.  Is this possible? Any ideas?

Regards
Mark

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to