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).


This method is added to the application object it overrides the default from ContextWrapper
	public void attachBaseContext(Context base) {


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

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

                 // 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