Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserDefaults instance for unit testing?

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?

like image 756
Takeshi Yokemura Avatar asked Oct 28 '25 02:10

Takeshi Yokemura


1 Answers

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")
like image 56
grigorevp Avatar answered Oct 30 '25 16:10

grigorevp



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!