6

Basically every time I have to execute an AndroidTest that makes use of mock location provider I need to manually check the box on device emulator: Settings--> mock locations. How to automate this task directly from the android test? Is there any way using espresso/uiautomator/something else?

5
  • One half of a possible answer: stackoverflow.com/questions/36339817/… Sep 28, 2016 at 16:51
  • Thanks I have added a comment on that question. Let's see...
    – Daniele
    Sep 28, 2016 at 17:15
  • Have you tried to take that adb command and add it to developer.android.com/studio/run/… as a Before Launch Operation Sep 28, 2016 at 17:24
  • @MorrisonChang nice hint. I can try but anyway I really don't like it so much because not portable. I would prefer a more "standard" approach. That should be possible somehow I think.
    – Daniele
    Sep 28, 2016 at 17:41
  • Not sure what you mean by "standard" unless you mean an officially documented thing to do via adb. Sep 28, 2016 at 18:03

1 Answer 1

6

I managed to do that in the way I wanted. Thanks to the links posted on comments. I added in my gradle file the following snippet:

task enableMockLocationForTestsOnDevice(type: Exec) {
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    def sdkDir = properties.getProperty('sdk.dir')
    def adb = "$sdkDir/platform-tools/adb"
    description 'enable mock location on connected android device before executing any android test'
    commandLine "$adb", 'shell', 'appops', 'set', 'indian.fig.whatsaround', 'android:mock_location', 'allow'
}

afterEvaluate {
    // Note: the app must be already installed on device in order to this to run!
    connectedDebugAndroidTest.dependsOn enableMockLocationForTestsOnDevice
    connectedAndroidTest.dependsOn enableMockLocationForTestsOnDevice
}


// execute android tests before realising a new apk
tasks.whenTaskAdded { task ->
    if (task.name == 'assembleRelease') {
        task.dependsOn('enableMockLocationForTestsOnDevice')
        task.dependsOn('testReleaseUnitTest') // Run unit tests for the release build
        task.dependsOn('connectedAndroidTest') // Installs and runs instrumentation tests for all flavors on connected devices.

    }
}

If you also need to run the task before launching the app via android studio you need to add it as before run editing the "run" configuration.

1
  • You can make sure that application is installed before enableMockLocationForTestsOnDevice is called by defining it as task enableMockLocationForTestsOnDevice(type: Exec, dependsOn: 'installDebugAndroidTest'). Jul 26, 2019 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.