Stubbing the Application Object in Android JUnit Testing

I have an Android app that I wrote to demonstrate unit testing techniques applied to Android code.  It has standalone JUnit tests for the code that is not dependent upon Android and Android JUnit tests for the code that is.  Dependency injection is used wherever possible.  Android code is harder to mock than other platforms, however, mostly because your Activity and Application are called by the OS and don’t support parameters in their constructors.  My first tactic to inject dependencies involved passing flags in the Activities’ Intents and having each Activity set up class factories with either the production classes or stubs, depending on the value of the flags.  This proved cumbersome.  For instance, if the factory has already been given an instantiation, say, from a different activity, should a request to set a new instantiation overwrite the old one?  My next try moved the factory set-up to the Application.  Since there is only one Application object per app, this solved the multiple Activity problem.  However, creation of the Application is done by the OS and the Application lifetime might span the lifetime of multiple Activities or test runs.  I was left with the same problem of determining whose factory initialization should be honored, either the Application’s or the Android JUnit Test Case’s.  In the end, the answer was simple and I’m surprised I didn’t think of it sooner.  All I needed was a link seam.  In the Android JUnit test project, I declared an Application class with the same name and package as specified in the Android manifest.  When the Android JUnit tests run, the stub Application is invoked and does nothing.  Here, I depend on each JUnit test to set up the factories with the stubs they need.  When the actual app runs, the real Application, that sets up the factories with production classes, is invoked.