简体   繁体   English

如何在Android项目中运行具有新风格的MockApplication?

[英]How to run MockApplication of a new flavor in Android project?

My app have two flavors. 我的应用程序有两种风格。 For sake of Espresso testing I created another flavor called mock in order to mock server response and create something that I would like to test against with. 为了进行Espresso测试,我创建了另一种名为“ mock ,以模拟服务器响应并创建要测试的对象。

So build.gradle file of my app project looks like this: 因此,我的应用程序项目的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'
        }
    }
}

I have created a Mock folder, it has its own manifest.xml file and it looks like this: 我创建了一个Mock文件夹,它有自己的manifest.xml文件,看起来像这样:

在此处输入图片说明

My Manifest file: 我的清单文件:

<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>

Before running the app, I set my build variant on mockDebug . 在运行该应用程序之前,我将构建变体设置为mockDebug I run the app and application gets installed on emulator. 我运行该应用程序,然后在模拟器上安装了该应用程序。 I confirm this build variant has installed because I have changed the name of it. 我确认已经安装了此构建变体,因为我已经更改了它的名称。 However, it seems my MockApplication never gets called although I have defined it in Manifest file. 但是,尽管我已经在清单文件中定义了我的MockApplication ,但似乎从未调用过它。 The reason is I don't see those things that I have logged. 原因是我看不到已记录的那些内容。

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();
    }

....
}

You can use a custom test runner to load the MockApplication . 您可以使用自定义测试运行器加载MockApplication No flavors required. 不需要口味。

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);
  }
}

Then, use it in your build.gradle file: 然后,在build.gradle文件中使用它:

testInstrumentationRunner 'com.example.MockUnitRunner'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM