I have a class which I want to test. It uses UserDefaults in its logic. I know I have to inject a test double to test it, but I want to make it without too much effort.
If it's possible to make a temporary UserDefaults instance which is only valid during the unit testing, that will be the best. Or do I have to write a wrapper for mocking eventually?
Yes, UserDefaults(suiteName: ) is what you are looking for. And you can declare it in your tests like so:
private class MockUserDefaults : UserDefaults {
  
  convenience init() {
    self.init(suiteName: "MockUserDefaults")!
  }
  
  override init?(suiteName suitename: String?) {
    UserDefaults().removePersistentDomain(forName: suitename!)
    super.init(suiteName: suitename)
  }
  
}
Removing persistent domain is helpful for avoiding colliding data from some previous test runs.
And then use it as usual:
MockUserDefaults.standard.setValue("Whatever", forKey: "SomeKey")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With