如何编写取决于位置更新的Android单元测试?

时间:2011-05-24 17:48:28

标签: android unit-testing gps location

我有一个应用程序,显示对应于该位置的Maidenhead网格方块。我想为此功能编写一个单元测试。

我创建了一个模拟位置提供程序。当我将模拟提供程序粘贴到我的应用程序中时,我在显示屏上看到预期的Maidenhead网格方块。当我将模拟提供程序粘贴到我的测试项目中并检查视图时它永远不会更新,即使我调用Thread.sleep()或waitOnIdleSync()。

我会直接测试计算实际网格方块的方法,但它是私有的,并且没有办法测试私有方法。我在网上看到的用于检查视图的单元测试的所有示例代码都是针对计算器之类的应用程序,其中活动是通过虚假按钮按下来触发的。

以下是测试的代码:

    public void testMaidenhead() {
        // this is a single test which doesn't really validate the algorithm
        // identifying a bunch of edge cases would do that
        publishMockLocation();
        final String expectedMH = "CM87wk";
        // TODO: checking the textview does not work
        TextView mhValueView = (TextView) mActivity.findViewById(org.twilley.android.hfbeacon.R.id.maidenheadValue);
        String actualMH = mhValueView.getText().toString();
        // final String actualMH = mActivity.gridSquare(mLocation);
        assertEquals(expectedMH, actualMH);
    }

以下是发布模拟位置的代码:

    protected void publishMockLocation() {
        final double TEST_LONGITUDE = -122.084095;
        final double TEST_LATITUDE = 37.422006;
        final String TEST_PROVIDER = "test";
        final Location mLocation;
        final LocationManager mLocationManager;

        mLocationManager = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE);
        if (mLocationManager.getProvider(TEST_PROVIDER) != null) {
            mLocationManager.removeTestProvider(TEST_PROVIDER);
        }
        if (mLocationManager.getProvider(TEST_PROVIDER) == null) {
            mLocationManager.addTestProvider(TEST_PROVIDER, 
                false, //requiresNetwork,
                false, // requiresSatellite,
                false, // requiresCell,
                false, // hasMonetaryCost,
                false, // supportsAltitude,
                false, // supportsSpeed,
                false, // supportsBearing,
                android.location.Criteria.POWER_MEDIUM, // powerRequirement
                android.location.Criteria.ACCURACY_FINE); // accuracy
        }
        mLocation = new Location(TEST_PROVIDER);
        mLocation.setLatitude(TEST_LATITUDE);
        mLocation.setLongitude(TEST_LONGITUDE);
        mLocation.setTime(System.currentTimeMillis());
        mLocation.setAccuracy(25);
        mLocationManager.setTestProviderEnabled(TEST_PROVIDER, true);
        mLocationManager.setTestProviderStatus(TEST_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
        mLocationManager.setTestProviderLocation(TEST_PROVIDER, mLocation);
    }

任何帮助都会非常感激。提前谢谢!

杰克。

1 个答案:

答案 0 :(得分:1)

单元测试不会使您的手机伪造其GPS位置,因此它会向您显示您要测试的位置的Maidenhead。单元测试将是:编写一个采用WGS84 GPS坐标并输出Maidenhead的函数,并为一系列输入位置和输出编写几个测试,以确保您的功能可以根据需要运行。

测试实际的Android活动将是集成或验收测试,但Maidenhead功能的实际坐标应该在您进行单元测试时起作用。

相关问题