3

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?

1 Answers1

4

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")
grigorevp
  • 631
  • 6
  • 13