Robolectric Unit Test failing with Android Studio 2.3 updates

时光总嘲笑我的痴心妄想 提交于 2019-11-30 08:58:17
Eugen Martynov

Set it by default, so every new test configuration that you create will inherit it:

Run > Edit Configurations... > Defaults > Android JUnit

in Working directory enter: $MODULE_DIR$

Android studio is looking at APP folder to run tests from AS 2.3 version. If you have Custom Roboelectric Runner extending RoboelectricTestRunner, you can override the working directory inside that, instead of setting WORKING DIR from edit configurations every time.

Here is my code.

`public class CustomRobolectricRunner extends RobolectricTestRunner {

// Build output location for Android Studio 2.2 and older
private static final String BUILD_OUTPUT = "build/intermediates";

// Build output location for Android Studio 2.3 and newer
private static final String BUILD_OUTPUT_APP_LEVEL = "app/build/intermediates";

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

@Override
protected AndroidManifest getAppManifest(Config config) {
    FileFsFile res = FileFsFile.from(BUILD_OUTPUT, "/res/merged", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE);
    FileFsFile assets = FileFsFile.from(BUILD_OUTPUT, "assets", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE);
    FileFsFile manifest = FileFsFile.from(BUILD_OUTPUT, "manifests", "full", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, "AndroidManifest.xml");

    // If above files does not exist in the specified paths, look them at the app folder level. This is needed
    // as Android studio 2.3 changed the working directory.
    if (!manifest.exists()) {
        manifest = FileFsFile.from(BUILD_OUTPUT_APP_LEVEL, "manifests", "full", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, "AndroidManifest.xml");
    }

    if (!res.exists()) {
        res = FileFsFile.from(BUILD_OUTPUT_APP_LEVEL, "/res/merged", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE);
    }

    if (!assets.exists()) {
        assets = FileFsFile.from(BUILD_OUTPUT_APP_LEVEL, "assets", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE);
    }

    AndroidManifest androidManifest = new AndroidManifest(manifest, res, assets) {
        @Override
        public Class getRClass() {
            return R.class;
        }

        public int getTargetSdkVersion() {
            /**
             * Lollipop is currently the highest version supported in 3.0.
             */
            return Build.VERSION_CODES.LOLLIPOP;
        }
    };

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