How do I specify custom /res directory in Robolect

2019-05-21 22:43发布

问题:

My unit tests and my android app live in separate projects.

With Robolectric 1, I could specify my /res directory location like so:

public class MyTestRunner extends RobolectricTestRunner {
    public MyTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass, "../app/AndroidManifest.xml", "../app/res");
    }
}

How do I specify the /res directory location in Robolectric 2.2?

回答1:

Use RobolectricTestRunner#getAppManifest(Config):

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

@Override
protected AndroidManifest getAppManifest(Config config) {
    return new AndroidManifest(
            Fs.fileFromPath("../app/AndroidManifest.xml"),
            Fs.fileFromPath("../app/res"),
            Fs.fileFromPath("../app/assets"));
}


回答2:

I had this same question a while ago, all you have to do is annotate your test class with:

@Config(manifest = "../app/AndroidManifest.xml")

and the dependencies will be picked up for you from your manifest.

PS. also make sure you have annotated your test class with @RunWith(RobolectricTestRunner.class) and your methods with the appropriate JUnit annotations (@Before, @Test, @After etc.) as well (just in case you haven't and forgot).