[英]Mocking NSBundle in Swift TDD
Is it possible to mock an applications NSBundle to return predictable results during TDD? 是否可以模拟应用程序NSBundle在TDD期间返回可预测的结果?
For example: 例如:
I want to test that my application handles when a file is not saved to the NSBundle: 我想测试我的应用程序在文件未保存到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")
}
Is it possible to mock the NSBundle.mainBundle() to return false for a pathForResource? 是否可以模拟NSBundle.mainBundle()为pathForResource返回false?
As it stands, NSBundle.mainBundle()
is a hard-coded dependency. 就目前而言,
NSBundle.mainBundle()
是一个硬编码的依赖项。 What we'd like is the ability to specify any bundle, perhaps with mainBundle as the default. 我们想要的是指定任何包的能力,可能将mainBundle作为默认值。 The answer is Dependency Injection .
答案是依赖注入 。 Let's use the preferred form of Constructor Injection, and take advantage of Swift's default parameters:
让我们使用构造函数注入的首选形式,并利用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")
}
}
Now a test can instantiate a ProfileImageGetter and specify any bundle it likes. 现在,测试可以实例化ProfileImageGetter并指定它喜欢的任何包。 This could be the test bundle, or a fake.
这可能是测试包,也可能是假的。
Specifying the test bundle would allow you to have a situation where profileImage.png doesn't exist. 指定测试包将允许您具有不存在profileImage.png的情况。
Specifying a fake would let you stub the result of calling pathForResource()
. 指定伪造将允许您存根调用
pathForResource()
的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.