Skip to Content

Some great in depth turtorials and slide for Android tasks »
« Using CSS precedence
submit to reddit

I have been setting up unit testing for an existing project of late and when testing services I ran into problems setting up the application and base context references. Searching around – I wasn’t able to find a way to do this, hence I am noting it down to make it (hopefully) easier for you..

Setting the Application context in the test unit setUp() enabled me to get the Application object but many other calls did not work (e.g. getPackageName()). To properly setup the application object we need to set the Base Context for the application object. This can be done by overriding attachBaseContext(Context base) in the application object and making it public.

Of course you shouldn’t really have to change your source to run tests – but in practice it happens anyways (e.g. making methods public to call them from the test).

Application

This method is added to the application object it overrides the default from ContextWrapper
        @Override
	public void attachBaseContext(Context base) {
		super.attachBaseContext(base);
	}

DownloadServiceTest

public class DownloadServiceTest extends ServiceTestCase<DownloadService> {
	DownloadService _downloadService;
	public DownloadServiceTest() {
		super(DownloadService.class);
	}
	public DownloadServiceTest(Class<DownloadService> activityClass) {
		super(activityClass);
		
	}

	protected void setUp() throws Exception {
		super.setUp();
		MyPODApplication myPODApplication = new MyPODApplication();// the application object
                // the overrided method to attach the context - we pass the Context provided by getSystemContext();
		myPODApplication.attachBaseContext(getSystemContext());
		setApplication(myPODApplication);
		
	        getApplication().onCreate();
	        setContext(getApplication());
	    
		Intent i = new Intent(getSystemContext(),DownloadService.class);
		i.setAction(Globals.INTENT_START_DOWNLOADS);
		Log.d(DownloadService.class.getSimpleName(), "dl svc started");
		startService(i);

                 // should use a service binder here
		_downloadService = getService();  
	}  
        // more test methods here
}

No comments yet!

You can be legendary and add one ...

All spam will be deleted - don't waste my time and yours. Fackbook profiles posted will be reported to FB as spam accounts


Allowed HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*

By submitting a comment you grant Sentinel Web Technologies a perpetual license to reproduce your words and name/web site in attribution. Inappropriate and irrelevant comments will be removed at an admin’s discretion. Your email is used for verification purposes only, it will never be shared.

Some great in depth turtorials and slide for Android tasks »
« Using CSS precedence