Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing UserDefaults-generated plist file when running unit tests

I'm testing a class that depends on an instance of UserDefaults. In following this sample code found here, I create and setup the instance like so:

override func setUp() {
    super.setUp()
    defaults = UserDefaults(suiteName: #file)
    defaults.removePersistentDomain(forName: #file)
}

After running the tests, a plist file is created within the same directory as this test class. If my testing file is named TestFile.swift the plist is given the name TestFile.swift.plist. I'm pretty sure this is generated at the call of the suiteName: initializer above. My question is: how do I remove this file once the tests have completed? I've tried making calls to removeSuite(named: #file), removeVolatileDomain(forName: #file), and removePersistentDomain(forName: #file) within the test's tearDown method but no luck. Calling synchronize() didn't seem to help either.

like image 639
WongWray Avatar asked May 21 '26 02:05

WongWray


1 Answers

Change your suiteName to a string literal, rather than #file. I'm unclear why, but using #file (which should just resolve to your file name) behaves different than passing a string constant. I'd also recommend calling removePersistentDomain in tearDown:

override func setUp() {
    super.setUp()
    defaults = UserDefaults(suiteName: "MyTestClass")
}

override func tearDown() {
    super.tearDown()
    defaults.removePersistentDomain(forName: "MyTestClass")
    …
}
like image 133
robmathers Avatar answered May 23 '26 15:05

robmathers



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!