How to set Allow Mock Location on Android Device before executing AndroidTest with uiautomator and espresso?

前端 未结 1 1763
谎友^
谎友^ 2020-12-06 19:47

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 location

1条回答
  •  悲&欢浪女
    2020-12-06 20:11

    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.

    0 讨论(0)
提交回复
热议问题