如何在Android项目中运行MockApplication的新风味?

时间:2016-02-22 19:48:29

标签: android android-espresso

我的应用有两种口味。为了Espresso测试,我创建了另一种名为mock的风格,以模拟服务器响应并创建我想要测试的内容。

我的应用项目的build.gradle文件如下所示:

android {

    useLibrary 'org.apache.http.legacy'

    sourceSets {
        main {
            res.srcDirs = [
                    'src/main/res', 'src/main/res-flags', ...
            ]
        }

        test {
            res.srcDirs = ['src/test/resources']
        }
    }

    defaultConfig {
        applicationId "com.my.package_1"
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
    }

    productFlavors {
        mock {
            applicationId "com.mock.package"
            ...
        }

        flavor_1 {
            applicationId "com.my.package_1"
            ...
        }

        flavor_2 {
            applicationId "com.my.package_2"
            ...
        }
    }

    buildTypes {
        debug {
            // Setup default urls
            buildConfigField "String", "API_URL_BASE", "\"https://www.example_1.com\""

            // Enabling multidex support.
            multiDexEnabled true

            dexOptions {
                incremental true
                javaMaxHeapSize "4g"
            }
        }

        release {
            // Enable when testing proguard
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.release

            // Setup default urls
            buildConfigField "String", "API_URL_BASE", "\"https://www.example_2.com\""
        }

        applicationVariants.all { variant ->
            variant.outputs.each { v ->
                def f = v.outputFile
                def sha = 'git rev-parse --short HEAD'.execute().text.trim()
                def fname = f.name.replace(".apk", "-${defaultConfig.versionName}-${defaultConfig.versionCode}-${sha}.apk")
                v.outputFile = new File(f.parent, fname)
            }
        }
    }

    // Remove mockRelease as it's not needed.
    android.variantFilter { variant ->
        if(variant.buildType.name.equals('release')
                && variant.getFlavors().get(0).name.equals('mock')) {
            variant.setIgnore(true);
        }
    }

    // Always show the result of every unit test, even if it passes.
    testOptions.unitTests.all {
        testLogging {
            events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
        }
    }
}

我创建了一个Mock文件夹,它有自己的manifest.xml文件,它看起来像这样:

enter image description here

我的清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">

    <permission
        android:name="com.mock.passenger.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="com.mock.passenger.permission.MAPS_RECEIVE"/>

    <!-- Settings for GCM -->
    <permission
        android:name="com.mock.passenger.gcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="com.mock.passenger.gcm.permission.C2D_MESSAGE"/>

    <application
        android:name="com.mock.passenger.MockApplication"
        tools:replace="android:name">

        ...

    </application>

</manifest>

在运行应用程序之前,我在mockDebug上设置了构建变体。我运行应用程序,应用程序安装在模拟器上。我确认已安装此版本变体,因为我已更改它的名称。但是,虽然我已在Manifest文件中定义了它,但我的MockApplication似乎永远不会被调用。原因是我没有看到我记录的那些东西。

public class MockApplication extends MyApplication
{
    public static final String TAG = MockApplication.class.getName();

    @Override
    public void onCreate()
    {
        Logger.debug(TAG, "*********************");
        Logger.debug(TAG, "** MockApplication **");
        Logger.debug(TAG, "*********************");

        super.onCreate();
    }

....
}

1 个答案:

答案 0 :(得分:0)

您可以使用自定义测试运行器加载MockApplication。不需要口味。

public class MockTestRunner extends AndroidJUnitRunner {
  @Override
  public Application newApplication(
      ClassLoader cl, String className, Context context)
      throws InstantiationException, 
             IllegalAccessException, 
             ClassNotFoundException {
    return super.newApplication(cl, MockApplication.class.getName(), context);
  }
}

然后,在build.gradle文件中使用它:

testInstrumentationRunner 'com.example.MockUnitRunner'

更多信息:http://blog.sqisland.com/2015/12/mock-application-in-espresso.html