Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resources$NotFoundException when using Robolectric with Gradle

I've been following this tutorial on setting up Robolectric to test my Android Gradle project.

I keep hitting this error:

android.content.res.Resources$NotFoundException: no such label com.mypackage.dev:string/app_name

By downloading the sample project from the tutorial I've established that the problem is my productFlavors (dev, staging, production). Adding flavors to the working sample project causes the same issue. You can see an outline of my build.gradle in this answer.

I've seen various answers (e.g. here) which suggest I need to specify the sourceSets for each flavor. I've tried lots of combinations but can't quite get it correct. Can anybody help?

The other thing confusing me is that all the Robolectric samples I've seen seem to be specifying the sourceSets and dependencies for "instrumentTest", even though the Robolectric tests are always only in the "test" folder. In my case I already have Robotium tests in the instrumentTest folder, and I don't see why I would need to add Robolectric dependencies for the Robotium code.

like image 503
Dan J Avatar asked Feb 28 '14 17:02

Dan J


1 Answers

I stumbled upon the same problem (resources not found) and found a solution on the robolectric source. There is a setter for PackageName, so in my custom test runner I set the package name before returning the manifest. Something like:

@Override protected AndroidManifest getAppManifest(Config config) {
    String manifestProperty = System.getProperty("android.manifest");
    if (config.manifest().equals(Config.DEFAULT) && manifestProperty != null) {
        String resProperty = System.getProperty("android.resources");
        String assetsProperty = System.getProperty("android.assets");
        AndroidManifest manifest = new AndroidManifest(Fs.fileFromPath(manifestProperty), Fs.fileFromPath(resProperty),
                Fs.fileFromPath(assetsProperty));
        manifest.setPackageName("com.mypackagename");
        return manifest;
    }
    return super.getAppManifest(config);
}

I hope this helps.

like image 130
John Nilsen Avatar answered Nov 19 '22 18:11

John Nilsen