How to prevent ActivityUnitTestCase from calling Application.onCreate?

后端 未结 2 1151
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 02:24

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

相关标签:
2条回答
  • 2020-12-30 02:52

    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.

    0 讨论(0)
  • 2020-12-30 03:04

    Roboguice had the same issue. Check it here.

    0 讨论(0)
提交回复
热议问题