Unit testing Activity.startService() call?

后端 未结 1 1152
时光取名叫无心
时光取名叫无心 2020-12-19 03:08

Attempting to write my first Android-by-TDD app (I\'ve written a few small Android apps without TDD, so am familiar with the environment), but I can\'t seem to get my head a

相关标签:
1条回答
  • 2020-12-19 03:35

    Just to summarise the conversation with Brian Dupuis in comments, the problem was that MockContext doesn't provide facilities that are required by the test instrumentation in order to correctly call onCreate(). Switch from MockContext to ContextWrapper solved this problem.

    The working test therefore looks like this:

    public void testStartServiceOnInit () {
        final AtomicBoolean serviceStarted = new AtomicBoolean(false);
        setActivityContext(new ContextWrapper(getInstrumentation().getTargetContext()) {
            @Override
            public ComponentName startService(Intent service) {
                Log.v("mockcontext", "Start service: " + service.toUri(0));
                if (service.getComponent().getClassName().equals ("net.meridiandigital.tasks.TasksService"))
                    serviceStarted.set(true);
                return service.getComponent();
            }
        });
        startActivity(new Intent(), null, null);
        assertTrue ("Service should have been started", serviceStarted.get());
    }
    
    0 讨论(0)
提交回复
热议问题