Search code examples
swiftxcodeunit-testingxctestuserdefaults

What are the consequences of using UserDefaults.standard in tests?


Assuming that in our test scheme we have execute in parallel on simulator unchecked.

Would the test below ever be flakey?

class ExampleTests: XCTestCase {
        override func setUp() {
            super.setUp()
            UserDefaults.clear()
        }

        func testSomethingWithUserDefaults() {
            UserDefaults.standard.setValue("Hola", forKey: "exampleKey")
            ExampleClass.doSomethingThatUsesUserDefaults()
            XCTAssertEqual(ExampleClass.foo, expectedValue)
        }

        override class func tearDown() {
            UserDefaults.clear()
            super.tearDown()
        }

I understand it's better to either stub the UserDefaults or create a new instance so our tests can be run in parallel but I'd like to ascertain the level of importance here. Will this merely block us from running our test in parallel in the future or will it result in flakey tests without applying this setting?


Solution

  • The test, run in isolation, will work. But here's another problem: it aggressively clears user defaults. This will cause problems for anyone who wants to do manual testing after running this test.

    A safer approach would be to have setUp() remember the current value (if any), then restore it in tearDown().

    The safest approach would be to use a fake.