2011-05-24 84 views
1

我有一个应用程序,显示对应于该位置的Maidenhead网格广场。我想为这个功能编写一个单元测试。如何编写依赖位置更新的Android单元测试?

我创建了一个模拟位置提供程序。当我将模拟提供程序粘贴到我的应用程序中时,我在显示屏上看到预期的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); 
    } 

任何帮助,将深深地感激。先谢谢你!

Jack。

回答

1

单元测试不会让您的手机假冒其GPS位置,因此它会显示您想要测试的位置的Maidenhead。单元测试将是:编写一个函数,它需要WGS84 GPS坐标并输出Maidenhead,并为一系列输入位置和输出编写几个测试,以确保您的函数能够按需要工作。

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

+0

对不起,没有得到更快!我已经写了测试,以检查使用地球上各种麻烦的点的Maidenhead代码。不过,我误解了测试与集成或验收测试之间的差异。谢谢! – 2012-12-27 19:42:18