Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Unit Test for UserDefaults

I have 2 functions where one basically retrieves string in User Defaults and another writes the string in User Defaults. I'm not able to understand that should I do the unit test or no? and I'm pretty new to the concept for Unit testing.

I scoured the internet for testing user defaults but I was advised to mock the test in the end.

My question is If there is a way to test User Defaults what is the best way to do it?

Constants and Structs

let defaults = UserDefaults.standard
let defaultinformation = "ABCDEFG"

struct Keys {
    static let Information = "Information"
}

Function where saves Information

func SetDefaultInformation() {
    defaults.set(defaultinformation, forKey: Keys.Information)

}

Function where retrieves Information

func checkForInformation() -> String {
    let Information = defaults.value(forKey: Keys.Information) as? String ?? ""
    return Information
}

Thanks in Advance

like image 694
Kane D Avatar asked Jun 11 '26 21:06

Kane D


2 Answers

should I do the unit test or no

No. You know what UserDefaults does and you know how it works and that it works. It is ridiculous to test Apple's code. Testing defaults.set is just as silly; you know exactly what it does and you know that it will do it.

What you want to test is your code: not your retrieval from UserDefaults per se, but your response to that retrieval. Give yourself methods such that you can see what you do when information is a String and what you do when information is nil. As you've been told, a trivial mock can supply the back end, playing the part of UserDefaults and giving back different sorts of result. Just don't let your tests involve the real UserDefaults.

like image 113
matt Avatar answered Jun 13 '26 16:06

matt


class ViewModel {
     func saveUserName(name: String, userDefaults: UserDefaults = UserDefaults.standard) {
            userDefaults.set(name, forKey: "username")
     }
}
class MockUserDefault: UserDefaults {
    var persistedUserName: String? = nil
    var persistenceKey: String? = nil
        
    override func set(_ value: Any?, forKey defaultName: String) {
        persistedUserName = value as? String
        persistenceKey = defaultName
    }
}
    
func testSavingUserName() {
    let viewModel = ViewModel()
    let mockUserDefaults = MockUserDefault()
    viewModel.saveUserName(name: "Oliver", userDefaults: mockUserDefaults)
        
    XCTAssertEqual("Oliver", mockUserDefaults.persistedUserName)
    XCTAssertEqual("username", mockUserDefaults.persistenceKey)
}
like image 42
Oliver Nguyen Avatar answered Jun 13 '26 17:06

Oliver Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!