Skip to content

Instantly share code, notes, and snippets.

@hacknicity
Created June 16, 2021 05:29
Show Gist options
  • Select an option

  • Save hacknicity/51727f46da4c6e82636981938e955b13 to your computer and use it in GitHub Desktop.

Select an option

Save hacknicity/51727f46da4c6e82636981938e955b13 to your computer and use it in GitHub Desktop.

Revisions

  1. hacknicity created this gist Jun 16, 2021.
    30 changes: 30 additions & 0 deletions UserDefaults+TestHelpers
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    import Foundation

    extension UserDefaults {

    /// Returns an empty `UserDefaults` instance suitable for unit testing.
    ///
    /// Based on https://www.swiftbysundell.com/posts/the-power-of-userdefaults-in-swift
    ///
    /// - Parameters:
    /// - functionName: name of the unit test function.
    /// - pathName: name of the unit test file (can be a full path).
    static func makeEmptyInstance(for functionName: StaticString = #function, inFile fileName: StaticString = #file) -> UserDefaults {
    guard
    let baseFileName = "\(fileName)".split(separator: "/").last?.split(separator: ".").first,
    let testName = "\(functionName)".split(separator: "(").first
    else {
    fatalError("Could not create suite name from functionName '\(functionName)' and fileName '\(fileName)'")
    }

    let suiteName = "com.hacknicity.FTPZones.test.\(baseFileName).\(testName)"

    guard let userDefaults = self.init(suiteName: suiteName) else {
    fatalError("Could not create UserDefaults for suite name \(suiteName)")
    }

    userDefaults.removePersistentDomain(forName: suiteName)

    return userDefaults
    }
    }