如何解决如何使用 Swift 模拟最终类和静态函数以进行单元测试?
我有一个带有 static
函数的类。
UserAuthentication.swift
final class UserAuthentication {
/// Check is logged in
/// - Returns: boolean true is login,false not login
@objc public static func isLogin() -> Bool {
return true
}
}
我想为 checkTermAndCondition
函数编写一个单元测试,该函数在我的 HomeInteractor
类中调用它
HomeInteractor.swift
class HomeInteractor: HomeInteractorBusinessLogic {
var presenter: HomePresenterInterface!
var worker: HomeWorker = HomeWorker(with: HomeService())
func checkTermAndCondition() {
if UserAuthentication.isLogin() {
///do true case
} else {
///do fasle case
}
}
}
有人做过吗? 感谢您的任何帮助。
解决方法
您不能在 static
类上模拟 final
方法。
您应该将方法更改为 class
并使类成为非最终类,或者甚至更好,将 UserAuthentication
作为协议注入 HomeInteractor
并在您的单元测试中注入模拟类型而不是您真正的生产类型。
protocol UserAuthenticator {
/// Check is logged in
/// - Returns: boolean true is login,false not login
static func isLogin() -> Bool
}
final class UserAuthentication: UserAuthenticator {
@objc public static func isLogin() -> Bool {
return true
}
}
final class UserAuthenticationMock: UserAuthenticator {
static var shouldLogin: Bool = false
static func isLogin() -> Bool {
shouldLogin
}
}
class HomeInteractor: HomeInteractorBusinessLogic {
var presenter: HomePresenterInterface!
var worker: HomeWorker = HomeWorker(with: HomeService())
let userAuthenticator: UserAuthenticator.Type
init(userAuthenticator: UserAuthenticator.Type) {
self.userAuthenticator = userAuthenticator
}
func checkTermAndCondition() {
if userAuthenticator.isLogin() {
} else {
}
}
}
为您的产品代码注入 UserAuthentication.self
,而为测试注入 UserAuthenticationMock.self
。
let prodHomeInteractor = HomeInteractor(userAuthenticator: UserAuthentication.self)
let testHomeInteractor = HomeInteractor(userAuthenticator: UserAuthenticationMock.self)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。