I'm writing my first iOS unit tests (Xcode 5, iOS 6) and find that the results of the unit tests vary depending on what I've done in the Simulator lately. E.g. I click on a user in my contacts list in the Simulator, and now my "recent contacts" data in UserDefaults has one more object than before, even when I'm running unit tests.
For unit testing, it's not clean to have random user defaults data (I'm used to RoR tests with their own clean db). Besides, I might want to test specific states like having empty "recent contacts" data.
From looking at related questions here, I seem some possible answers that I'm not happy with.
These seem unnecessarily complicated for something that should be standard practice in unit tests. I don't want to repeat myself in every unit test. So, my questions are:
Using named suites like in this answer worked well for me. Removing the user defaults used for testing could also be done in func tearDown()
.
class MyTest : XCTestCase { var userDefaults: UserDefaults? let userDefaultsSuiteName = "TestDefaults" override func setUp() { super.setUp() UserDefaults().removePersistentDomain(forName: userDefaultsSuiteName) userDefaults = UserDefaults(suiteName: userDefaultsSuiteName) } }
Available iOS 7 / 10.9
Rather than using the standardUserDefaults you can use a suite name to load your tests
[[NSUserDefaults alloc] initWithSuiteName:@"SomeOtherTests"];
This coupled with some code to remove the SomeOtherTests.plist file from the appropriate directory in setUp
will archive the desired result.
You would have to design any objects to take your defaults objects so that there wouldn't be any side effects from the tests.
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