Skip to content

Instantly share code, notes, and snippets.

@msewell
Last active June 24, 2020 07:57
Show Gist options
  • Save msewell/9d8951c9a6eff813bd3b1aec1c13ad89 to your computer and use it in GitHub Desktop.
Save msewell/9d8951c9a6eff813bd3b1aec1c13ad89 to your computer and use it in GitHub Desktop.
AssertEquals via `dump(_:)`. Equate the unequatable!
import func XCTest.XCTAssertEqual
/// Writes the output of `dump(_:)` into a string and returns it.
func dumpToString(_ dumpee: Any) -> String {
var string = ""
dump(dumpee, to: &string)
return string
}
/// Asserts that the `dump(_:)` of the two inputs are equal.
func assertDumpEqual(_ dumpee1: @autoclosure () -> Any, _ dumpee2: @autoclosure () -> Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(dumpToString(dumpee1()), dumpToString(dumpee2()), file: file, line: line)
}
protocol Unequatable { }
struct MyUnequatable: Unequatable {}
//XCTAssertEqual(MyUnequatable(), MyUnequatable()) // 💥 Compiler error: "Value of protocol type 'Unequatable' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols"
assertDumpEqual(MyUnequatable(), MyUnequatable()) // ✅
// MARK: - A less trivial example using `Color`.
import struct SwiftUI.Color
// Tuples can't conform to `Equatable`.
let colors1: (Color, Color) = (.red, .red)
let colors2: (Color, Color) = (.red, .green)
// XCTAssertEqual(colors1, colors1) // 💥 Compiler error: "Type '(Color, Color)' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols"
assertDumpEqual(colors1, colors1) // ✅
assertDumpEqual(colors1, colors2) // ❌
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment