如何在测试用例中测试CLLocationManager的不同权限
问题描述:
我正在编写一个测试来测试CoreLocation
的相关功能。如果位置服务未启用,此功能将引发错误。如何在测试用例中测试CLLocationManager的不同权限
func someFunction() throws {
guard CLLocationManager.locationServicesEnabled() throw NSError.init(
domain: kCLErrorDomain,
code: CLError.Code.denied.rawValue,
userInfo: nil)
}
...
}
在我的测试,CLLocationManager.locationServicesEnabled()
总是true
。有没有办法测试false
的情况?
答
不是直接使用静态方法,而是将此调用包装在类中,并使该类采用协议,因此您的代码将取决于该接口而不是具体实现。
protocol LocationManager {
var islocationServicesEnabled: Bool { get }
}
class CoreLocationManager: LocationManager {
var islocationServicesEnabled: Bool {
return CLLocationManager.locationServicesEnabled()
}
}
然后你的函数(或类)应接收的依赖,而不是拥有它(依赖注入):
func someFunction(locationManager: LocationManager) throws {
guard locationManager.islocationServicesEnabled else {
//...
}
}
在您的测试,你可以通过一个“假”的LocationManager,并测试所有场景。 (在您的生产代码中,您通过CoreLocationManager。)
这是针对任何依赖关系的一般建议。