【问题标题】:How to send mock location coordinates when androidTest is running?androidTest运行时如何发送模拟位置坐标?
【发布时间】:2019-12-24 16:35:42
【问题描述】:

我正在开发一个基于 Here SDK 的导航应用。现在,当我进行集成测试(androidTest)时,我需要在 Android Emulator(Nexus 10 API 28)上模拟不同的 GPS 坐标。我尝试了很多不同的方法,但没有任何效果(LocationManager、Fusedlocationproviderclient、ADB shell appops set mock_location 等......唯一有效的是 ADB emu geo fix,但这还不够......)我没有在 Android 文档中找到有关位置/坐标测试的任何有用信息。有没有办法在测试运行时以编程方式更改和更新模拟器 GPS 坐标?

【问题讨论】:

    标签: java android android-gradle-plugin emulation


    【解决方案1】:

    此答案对我有用,并在此处发布以供您参考。随时对此进行改进并作为答案发布。我遇到了一个类似的阻塞点,在对 SO 进行研究之后,我得出了这个统一的答案。请参阅底部的一些 SO 相关答案的参考资料。

    它包括您提到的许多尝试,因此至少可以帮助您确定其他一些不相关的原因,如果它仍然对您不起作用。我在 Nexus 10 API 28 模拟器上运行了它。

    请注意,模拟器必须在运行测试之前运行,并且您的应用需要 已经安装;否则,gradle 'adb' 命令将失败。 (一个区域 进行改进)。

    这有两个部分:1) 更新您的 build.gradle 和 2) 模拟测试位置。

    对 build.gradle(应用程序)的更新

    (该任务只能在调试版本中执行 - 因为它是作为 'assembleDebug' 的依赖项添加的,所以我相信这已经完成。)

    // The objective of this task and supporting code is to enable mock locations
    // on the target emulator device.
    //
    // ** REPLACE 'APP PACKAGE NAME' with your app's package name. **
    
    // These tasks should be disabled in some way prior to release.
    
    task enableMockLocationForTestsOnDevice(type: Exec) {
       project.logger.lifecycle("------enableMockLocationForTestsOnDevice------\n")
    
    
       if (true) {
           project.logger.lifecycle("------enabled------\n")
           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', 'APP PACKAGE NAME', '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
    }
    
    tasks.whenTaskAdded { task ->
        if (task.name == 'assembleDebug') {
            task.dependsOn('enableMockLocationForTestsOnDevice')
        }
    }
    

    浓缩咖啡测试更新

    //...
    
    // This rule should be familiar - it's standard part of espresso test
    @Rule
    public ActivityTestRule<(your activity)> mActivityRule = new ActivityTestRule<>((your activity class));
    
    // ...
    
    // Utility invocation in test
    // start location updates - 25m/s (~55mph)
    LatLng startPos = new LatLng(39.0, -77.0);
    LocationUtils.startUpdates(mActivityRule.getActivity(),
            new Handler(Looper.getMainLooper()),
            startPos, 340, 25);
    
    // ...    
    
    // (In a test utility class in this example: LocationUtils.java)
    // Utility - uses SphericalUtil to maintain a position based on
    //           initial starting position, heading and movement value (in
    //           meters) applied every 1 second.  (So a movement value
    //           of 25 equates to 25m/s which equates to ~55MPH)
    public static void startUpdates(
        final Activity activity, final Handler mHandler, final LatLng pos, 
        final double heading, final double movement) {
    
    
        mHandler.postDelayed(new Runnable() {
            private LatLng myPos = new LatLng(pos.latitude,pos.longitude);
    
            @Override
            public void run() {
    
                Location mockLocation = new Location(LocationManager.GPS_PROVIDER); // a string
                mockLocation.setLatitude(myPos.latitude);  // double
                mockLocation.setLongitude(myPos.longitude);
                mockLocation.setAltitude(100);
                mockLocation.setTime(System.currentTimeMillis());
                mockLocation.setAccuracy(1);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
                }
    
                LocationServices.getFusedLocationProviderClient(activity).setMockMode(true);
                LocationServices.getFusedLocationProviderClient(activity).setMockLocation(mockLocation);
    
    
                // compute next position
                myPos = SphericalUtil.computeOffset(myPos, movement, heading);
                mHandler.postDelayed(this, 1000);
            }
        }, 1000);
    }
    

    参考
    Gradle 的东西:https://stackoverflow.com/a/39765423/2711811

    提到为什么需要 'adb 命令:https://stackoverflow.com/a/52698720/2711811

    【讨论】:

    【解决方案2】:

    我使用了之前的代码,但出现了下一个错误: Could not get unknown property 'connectedDebugAndroidTest' for project ':X' of type org.gradle.api.Project.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      相关资源
      最近更新 更多