簡體   English   中英

測試userDefaults和私有功能

[英]Testing userDefaults and private function

我正在使用Coordinator模式來處理ViewController。

在我的appCoordinator我通過用戶登錄狀態設置rootViewController

protocol Coordinatorbale {
    func coordinate()
}


class AppCoordinator: Coordinatorbale {
    init(){ .... }

    func coordinate() {
       let logedIn = UserDefaults.standard.bool(forKey: "user_logged_in")

        if logedIn {
            window.rootViewController = V1
        else {
            window.rootViewController = V2
        }
    }

}

我該如何測試?

如果我從coordinate函數中取出邏輯。 新的樂趣將是私人的,然后我仍然無法測試狀態。

private func setRootByUserState(logedIn: Bool) {
    if logedIn {
            window.rootViewController = V1
        else {
            window.rootViewController = V2
        }
}

所以我陷入了private方法或UserDefaults

如何對這種行為進行單元測試?

您可以將UserDefaults包裝在協議后面。

protocol PreferenceAware {
    var isLoggedIn: Bool { get set }
}

然后讓另一個類符合此protocol

struct UserDefaultsPreferences: PreferenceAware {
    private let userLoggedInKey = "user_logged_in"
    get {
        return UserDefaults.standard.bool(forKey: userLoggedInKey)
    }

    set {
        UserDefaults.standard.set(newValue, forKey: userLoggedInKey)
    }
}

然后,您的AppDelegate具有類型為PreferenceAware的變量,如下所示:

var prefenceContainer: PreferenceAware = UserDefaultsPreferences()

然后像這樣在您的方法中使用它

func coordinate() {
   let loggedIn = preferenceContainer.isLoggedIn

    if loggedIn {
        window.rootViewController = V1
    else {
        window.rootViewController = V2
    }
}

現在,為了進行測試,您可以創建一個符合PreferenceAware的測試對象,在AppDelegate更新您的preferenceContainer並根據需要對其進行控制。

struct MockPreferenceAware: PreferenceAware {
    var isLoggedIn: Bool
}

允許您在測試中執行以下操作:

func testLoggedIn() {
    let mock = MockPreferenceAware(isLoggedIn: true)
    appDelegate.preferenceContainer = mock

    //now you are sure of the path that your code will follow in the coordinate method
}

您還可以在用戶未登錄時測試流程:

func testNotLoggedIn() {
    let mock = MockPreferenceAware(isLoggedIn: false)
    appDelegate.preferenceContainer = mock

    //now you are sure of the path that your code will follow in the coordinate method
}

請注意,我目前不在編譯器附近(可怕的想法是:)),所以我沒有測試上面的語法錯誤,但是希望您能理解,並且希望對您有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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