【问题标题】:Is there a way to unit test Touch Id using XCTest?有没有办法使用 XCTest 对 Touch Id 进行单元测试?
【发布时间】:2015-08-13 01:14:51
【问题描述】:

有没有办法使用 XCTest 对 TouchId 的“evaluatePolicy”或“canevaluatePolicy”进行单元测试?我想以模拟器为基础进行单元测试。

谢谢

【问题讨论】:

    标签: ios unit-testing ios-simulator xctest touch-id


    【解决方案1】:

    我已经描述了一种为 Touch ID 代码 in this post 编写单元测试的方法。

    基本上,如果你有一些类似于这个的 Touch ID 管理类:

    final public class TouchIDManager {
    
        /// Authentication context object we use for Touch ID. Typically it's just a `LAContext` instance that is mocked when testing.
        internal var authenticationContext = LAContext()
    
        /**
         Checks Touch ID availability.
    
         - returns: Flag indicating if Touch ID is available
         */
        public func touchIDAvailable() -> Bool {
            return authenticationContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: nil)
        }
    
        /**
         Authenticates the user with Touch ID
    
         - parameter completion: Completion handler
             */
        public func authenticate(completion: (success: Bool) -> ()) {
            guard touchIDAvailable() else {
                completion(false)
                return
            }
            authenticationContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "Wanna Touch my ID?") {
                (success: Bool, error: NSError?) -> Void in
                completion(success: success)
            }
        }
    }
    

    您可以使用 StubLAContext 类简单地伪造 LAContext 行为:

    func testSuccessfulAuthentication() {
        /// A class faking Touch ID availability and successful user verification
        class StubLAContext: LAContext {
            override func evaluatePolicy(policy: LAPolicy, localizedReason: String, reply: (Bool, NSError?) -> Void) { reply(true, nil) }
            override func canEvaluatePolicy(policy: LAPolicy, error: NSErrorPointer) -> Bool { return true }
        }
    
        let manager = TouchIDManager()
        manager.authenticationContext = StubLAContext()
    
        manager.authenticate { (success) in
            XCTAssertTrue(success)
        }
    }
    

    显然,这个特定的测试并没有做太多的事情,但它可能是一个很好的起点来测试您在应用程序中拥有的其他与 Touch ID 相关的逻辑。

    【讨论】:

    • 我看到了你的帖子,这对我来说是一个很好的起点。我被困的地方是试图在 LAErrorCode 上编写测试。有什么建议吗?
    • 您具体要测试什么?我想你可以让存根返回特定测试所需的任何错误。
    • 我正在尝试解决如何为特定错误制作存根。目前哪个错误并不重要,因为它们存储在枚举中。
    • 抱歉,我仍然不明白您要为什么创建存根:您可以覆盖 LAContext 存根中的任何方法并使其返回任何错误,以防您尝试测试您的代码如何响应此特定错误。
    • @AlexStaravoitau 我认为 Greg 的意思是问如何将“错误:NSErrorPointer”设置为 LAError.biometryLockout 之类的东西?这也是我感兴趣的
    猜你喜欢
    • 2011-03-23
    • 2010-11-13
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多