Robolectric not using test application

爷,独闯天下 提交于 2019-12-20 12:38:33

问题


According to this link I can create a test application which Robolectric will automatically start using in tests. I cannot get this to work.

I am using Dagger for dependency injection and have created injection wrapper classes for Activity and Application. Then each of my activities extends the wrapper activity class instead of plain old Activity.

The problem I am having is that, in tests, the dependencies provided by the Application modules can't be resolved and so the tests fail. This is because most of our tests are just building an activity (using Robolectric.buildActivity()) and aren't running from an Application.

I was hoping to somehow modify the Robolectric testrunner to run our tests under the Application. Either that or use a test application as outlined in that link above.

I've created a test application and am still getting the same test errors because the tests aren't running under this test application. I've tried moving the test application to different packages etc, but nothing changes.

I'm looking for some advice on how to go about doing what I want. Would be particularly interested in those with experience with Dagger and how they go about testing.


回答1:


It's really simple in Robolectric 3.0, you add it directly to the @Config annotation.

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21,application = TestApplication.class)
public class ActivityTest {



回答2:


Apologies, forgot about this. To resolve this I created a TestApplication residing along side the tests. Then I modified our TestRunner (which extends the RobolectricTestRunner) to:

public class TestRunner extends RobolectricTestRunner {

    public TestRunner(final Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    ...

    @Override
    protected Class<? extends TestLifecycle> getTestLifecycleClass() {
        return MyTestLifecycle.class;
    }

    public static class MyTestLifecycle extends DefaultTestLifecycle {
        @Override
        public Application createApplication(final Method method, final AndroidManifest appManifest) {
            // run tests under our TestApplication
            return new TestApplication();
        }
    }

    ...

}



回答3:


You can configure it in the file org.robolectric.Config.properties

application = <fully qualified name of the Application>

See http://robolectric.org/configuring/



来源:https://stackoverflow.com/questions/21725309/robolectric-not-using-test-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!