Skip to content

Instantly share code, notes, and snippets.

@hacknicity
Created June 16, 2021 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hacknicity/51727f46da4c6e82636981938e955b13 to your computer and use it in GitHub Desktop.
Save hacknicity/51727f46da4c6e82636981938e955b13 to your computer and use it in GitHub Desktop.
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment