[英]Is there a way to unit test Touch Id using XCTest?
Is there a way to unit test TouchId's "evaluatePolicy" or "canevaluatePolicy" using XCTest? 有没有办法使用XCTest对TouchId的“evaluatePolicy”或“canevaluatePolicy”进行单元测试? I want to unit test using simulator as base.
我想用模拟器作为基础进行单元测试。
Thanks 谢谢
I have described one way of writing unit test for Touch ID code in this post . 我已经描述了在这篇文章中为Touch ID代码编写单元测试的一种方法。
Basically, if you have some Touch ID managing class similar to this one: 基本上,如果你有一个类似于这个的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)
}
}
}
You can simply fake the LAContext
behaviour with a StubLAContext
class: 您可以使用
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)
}
}
Clearly this particular test doesn't do much, but it might be a good starting point to test other Touch ID related logic you have in your application. 显然,这个特定的测试没有多大作用,但它可能是测试应用程序中其他Touch ID相关逻辑的一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.