[英]Mocking NSBundle in Swift TDD
是否可以模拟应用程序NSBundle在TDD期间返回可预测的结果?
例如:
我想测试我的应用程序在文件未保存到NSBundle时处理:
//Method to test
func getProfileImage() -> UIImage {
if let profileImagePath = getProfilePhotoPath() {
UIImage(contentsOfFile: profileImagePath)
}
return UIImage(named: "defaultProfileImage")
}
private func getProfilePhotoPath() -> String? {
return NSBundle.mainBundle().pathForResource("profileImage", ofType: "png")
}
是否可以模拟NSBundle.mainBundle()为pathForResource返回false?
就目前而言, NSBundle.mainBundle()
是一个硬编码的依赖项。 我们想要的是指定任何包的能力,可能将mainBundle作为默认值。 答案是依赖注入 。 让我们使用构造函数注入的首选形式,并利用Swift的默认参数:
class ProfileImageGetter {
private var bundle: NSBundle
init(bundle: NSBundle = NSBundle.mainBundle()) {
self.bundle = bundle
}
func getProfileImage() -> UIImage {
if let profileImagePath = getProfilePhotoPath() {
return UIImage(contentsOfFile: profileImagePath)!
}
return UIImage(named: "defaultProfileImage")!
}
private func getProfilePhotoPath() -> String? {
return bundle.pathForResource("profileImage", ofType: "png")
}
}
现在,测试可以实例化ProfileImageGetter并指定它喜欢的任何包。 这可能是测试包,也可能是假的。
指定测试包将允许您具有不存在profileImage.png的情况。
指定伪造将允许您存根调用pathForResource()
的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.