我使用 KIF 框架 ( http://github.com/kif-framework/KIF ) 进行 UI 测试 我需要模拟定位服务。
问题是位置服务在调用 KIF 方法 -beforeAll 之前启动。 所以现在 mock 为时已晚。
如有任何建议,我们将不胜感激。
最佳答案
在我的 KIF 目标中,我有一个 BaseKIFSearchTestCase : KIFTestCase
,我在其中覆盖了类别中的 CLLocationManager 的 startUpdatingLocation。
请注意,这是我做过的唯一一次类别覆盖,因为这通常不是一个好主意。但在测试目标中我可以接受。
#import <CoreLocation/CoreLocation.h>
#ifdef TARGET_IPHONE_SIMULATOR
@interface CLLocationManager (Simulator)
@end
@implementation CLLocationManager (Simulator)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
-(void)startUpdatingLocation
{
CLLocation *fakeLocation = [[CLLocation alloc] initWithLatitude:41.0096334 longitude:28.9651646];
[self.delegate locationManager:self didUpdateLocations:@[fakeLocation]];
}
#pragma clang diagnostic pop
@end
#endif // TARGET_IPHONE_SIMULATOR
#import "BaseKIFSearchTestCase.h"
@interface BaseKIFSearchTestCase ()
@end
@implementation BaseKIFSearchTestCase
//...
@end
更干净的方法是在您的应用程序目标中有一个 CLLocationManager
的子类,在您的测试目标中有另一个具有相同名称的子类,如上所示发送假位置。但是,这是否可能取决于您的测试目标是如何设置的,因为它实际上需要是一个应用程序目标,因为 Calabash 使用它。
另一种方式:
在您的项目中创建另一个配置“Testing”,克隆“Debug”
将
Preprocessor Macro
TESTING=1
添加到该配置。子类
CLLocationManager
在您要使用 CLLocaltionManger 的地方使用那个子类
有条件地编译那个类
#import "GELocationManager.h" @implementation GELocationManager -(void)startUpdatingLocation { #if TESTING==1 #warning Testmode dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ CLLocation *fakeLocation = [[CLLocation alloc] initWithLatitude:41.0096334 longitude:28.9651646]; [self.delegate locationManager:self didUpdateLocations:@[fakeLocation]]; }); #else [super startUpdatingLocation]; #endif } @end
在您的测试目标方案中选择新配置
还有一个选择:
可能是最好的:无需更改代码。
关于ios - 如何使用 KIF 框架模拟位置服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22560990/