簡體   English   中英

在Swift TDD中模擬NSBundle

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM