简体   繁体   English

如何在测试用例中测试CLLocationManager的不同权限

[英]How to test different permissions of CLLocationManager in test cases

I am writing a test to test CoreLocation related function. 我正在编写测试来测试CoreLocation相关的功能。 This function will throw an error if the location services is not enabled. 如果未启用位置服务,则此函数将引发错误。

func someFunction() throws {
    guard CLLocationManager.locationServicesEnabled() throw NSError.init(
            domain: kCLErrorDomain,
            code: CLError.Code.denied.rawValue,
            userInfo: nil)
    }
    ...
}

In my tests, CLLocationManager.locationServicesEnabled() is always true . 在我的测试中, CLLocationManager.locationServicesEnabled()始终为true Is there a way to test the false scenario? 有没有办法测试false情况?

Instead of using static methods directly, wrap this call in a class and make that class adopt a protocol, so your code will depend on that interface instead of the concrete implementation. 而不是直接使用静态方法,将此调用包装在类中并使该类采用协议,因此您的代码将依赖于该接口而不是具体实现。

protocol LocationManager {
    var islocationServicesEnabled: Bool { get }
}

class CoreLocationManager: LocationManager {
    var islocationServicesEnabled: Bool  {
        return CLLocationManager.locationServicesEnabled()
    }
}

Then your function (or class) should receive that dependency instead of owning it (dependency injection): 然后你的函数(或类)应该接收该依赖而不是拥有它(依赖注入):

func someFunction(locationManager: LocationManager) throws {
    guard locationManager.islocationServicesEnabled else {
        //...
    }
}

In your tests you can pass a "Fake" LocationManager and test all the scenarios. 在测试中,您可以传递“假”位置管理器并测试所有方案。 (In your production code you pass the CoreLocationManager.) (在您的生产代码中,您传递了CoreLocationManager。)

That's a general advice for any dependency. 这是任何依赖的一般建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM