18

I must be missing something here. The JavaDoc of ActivityUnitTestCase suggest that this test case tests an Activity in isolation from the system:

This class provides isolated testing of a single activity. The activity under test will be created with minimal connection to the system infrastructure, and you can inject mocked or wrappered versions of many of Activity's dependencies.

I was assuming that includes not actually starting the application. Moreover, it exposes a setApplication helper that one can presumably use to inject a mock application.

However, any ActivityUnitTestCase I start launches the (actual) application and calls its onCreate method. More precisely, the InstrumentationTestRunner seems to be doing that, and doing so even before I get a chance to setApplication in my test's setUp method! I didn't even notice that for quite a while, since it seems to happen at a point during test suite launch where not even Eclipse breakpoints are reached, but writing to the logs in onCreate reveals that it's actually called.

This is completely beyond me. Why would I want to use a mock app object when Android's test runner instantiates and executes the actual application anyway? This is even more problematic considering that the instrumentation runner runs in its own thread, and spawns the main application thread when doing so. This means there is a race condition between the test being executed and Application.onCreate being called. If you do anything in there that could affect your tests, e.g. writing to a shared preference file, then you're completely screwed, since your tests will randomly fail.

Am I missing something or is this simply a gross oversight in the test framework?

UPDATE This seems to affect ApplicationTestCase as well. Before my test case is even started, I can reach a breakpoint in my application class' onCreate. We start a fire-and-forget AsyncTask in there, which will randomly fail because I get no chance to mock it out (remember, that's before setUp is called on my test case). Here is the stack trace I see during this obscure invocation of onCreate:

Thread [<1> main] (Suspended (breakpoint at line 86 in QypeRadar))  
QypeRadar.onCreate() line: 86   
InstrumentationTestRunner(Instrumentation).callApplicationOnCreate(Application) line: 969   
ActivityThread.handleBindApplication(ActivityThread$AppBindData) line: 4244 
ActivityThread.access$3000(ActivityThread, ActivityThread$AppBindData) line: 125    
ActivityThread$H.handleMessage(Message) line: 2071  
ActivityThread$H(Handler).dispatchMessage(Message) line: 99 
Looper.loop() line: 123 
ActivityThread.main(String[]) line: 4627    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
Method.invoke(Object, Object...) line: 521  
ZygoteInit$MethodAndArgsCaller.run() line: 868  
ZygoteInit.main(String[]) line: 626 
NativeStart.main(String[]) line: not available [native method]  

Why does the test runner callApplicationOnCreate even though the docs clearly state:

The test case will not call onCreate() until your test calls createApplication(). This gives you a chance to set up or adjust any additional framework or test logic before onCreate().

That's a flat out lie--it doesn't give me the chance!

5
  • As far as I can tell, there is only two ways to fix this: 1) rewrite InstrumentationTestRunner to not do that call to callApplicationOnCreate and leave it to the test case to decide whether that's wanted or not. Not sure what effect that will have on other tests though. 2) Rewrite our onCreate method to be side effect free and idempotent (recall that it will be called twice, since for the test case to work you also have to call createApplication). Thoughts?
    – mxk
    Feb 16, 2011 at 10:30
  • So, I've created a custom test runner that bypasses callApplicationOnCreate, now everything works as expected for unit tests. For functional tests, I would still need the default test runner that performs a full launch, so I now have two test runners, which is a bit of a pain.
    – mxk
    Feb 16, 2011 at 16:24
  • Interesting write-up. Would it be simple enough to bypass callApplicationOnCreate only for the appropriate test case types, allowing you to create a patch for the test runner that you could send upstream? Feb 16, 2011 at 18:02
  • If you're using a build system or otherwise run your tests via the command line (i.e. ADB/Activity Manager), then this is straight forward: 1) keep your unit tests in a separate package from your functional tests; 2) when invoking adb shell am instrument, pair the package under test with the appropriate test runner. Of course this means there will be two separate tests runs, but that's fair enough I guess. Things get more complicated in Eclipse/ADT. Here you have to define for every single test case which test runner to use in the Eclipse run configuration.
    – mxk
    Feb 17, 2011 at 9:56
  • 3
    we got 2014 now. is there any better solution for this issue?
    – Piotr
    Apr 29, 2014 at 1:31

2 Answers 2

3

Roboguice had the same issue. Check it here.

2
  • 3
    +1 for the useful material, I didn't know about attachBaseContext before! However, it doesn't help: the test runner still invokes the no-arguments constructor, and if I remove that, I get an exception: "InstantiationException -- newInstance failed: no <init>()". If I leave the no-args ctor in, the onCreate is still being called on the original app object, regardless whether I call setApplication or not, so the problem remains.
    – mxk
    Feb 12, 2011 at 18:52
  • Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – nhaarman
    Jul 3, 2015 at 21:33
2

I'm doing tests with dagger, so probably this is your case too, since you probably want to just inject and do not call whatever is in Application.onCreate, so this one is works fine for me (api17+):

private Context mContext;
private Application mApplication;

@Override
protected void setUp() throws Exception {
    super.setUp();

    mContext = new ContextWrapper(getInstrumentation().getTargetContext()) {
        @Override
        public Context getApplicationContext() {
            return mApplication;
        }
    };
    mApplication = new MyAppMock();
    mApplication.attachBaseContext(mContext); 

    setApplication(app);
}

public void testActivityCreated() {
    Intent intent = AboutActivity.createIntent(mContext);
    setActivityContext(mContext);
    startActivity(intent, null, null);
    assertNotNull(getActivity());
}

For < api16 you need to use reflection and call Application.attach(context) instead Application.attachBaseContext() to set Application.mLoadedApk, otherwise it will crash.

I have put everything together and made demo app that shows how to test with dagger: https://github.com/vovkab/dagger-unit-test

It also shows how to mock your application, works for any android version.

4
  • Have you been able to test the "dagger-unit-test" test class? I tried this approach myself but failed because Dagger complains that the TestModule doesn't have the target class registered-- it's seeing the target class as the anonymous class MyTestClass$2 instead of InjectableAppMock (which is what specified in the modules "inject" attribute of its "Module" annotation.
    – twelve17
    Sep 7, 2014 at 9:53
  • Not sure about what sample code you are talking about, class names you mentioned doesn't match nor this example nor example hosted on github. In my sample app hosted on github, I inject MainActivity class: @Module(injects = MainActivity.class). Yes it works fine, please take a look for example here: github.com/vovkab/dagger-unit-test
    – vovkab
    Sep 8, 2014 at 21:05
  • Apologies for not responding to this sooner. I obviously must have had the wrong code--I just got back to the project I was working on, and what I did realize was that I was missing the call to setActivityContext(mContext); from your example. Thanks!
    – twelve17
    Feb 25, 2015 at 1:30
  • I used code based on your dagger-unit-test on a device running version 16 (e.g. Build.VERSION_CODES.JELLY_BEAN). For this case, the attachBaseContext() override uses reflection to call "attach()" on the parent class. However, the parent "attach()" calls "attachBaseContext()", so I end up with infinite recursion. Should version 16 be included in the call to super.attachBaseContext(), perhaps?
    – twelve17
    Mar 18, 2015 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.