Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Created December 28, 2020 18:44
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 joemasilotti/b5b91ff28319a883bd50e3c3089893a0 to your computer and use it in GitHub Desktop.
Save joemasilotti/b5b91ff28319a883bd50e3c3089893a0 to your computer and use it in GitHub Desktop.
Using #function to record messages sent to Swift test doubles
import XCTest
class Tests: XCTestCase {
func test_visit_startsTheDelegate() {
let delegate = TestVisitDelegate()
let visitor = Visitor(delegate: delegate)
visitor.visit("/")
XCTAssertTrue(delegate.didCall("visitDidStart()"))
}
func test_visit_completesTheDelegate() {
let delegate = TestVisitDelegate()
let visitor = Visitor(delegate: delegate)
visitor.visit("/")
XCTAssertTrue(delegate.didCall("visitDidComplete()"))
}
}
class TestVisitDelegate: VisitDelegate {
func visitDidStart() {
record(#function)
}
func visitDidComplete() {
record(#function)
}
// MARK: Testing verification helpers.
private var methodsCalled: Set<String> = []
func didCall(_ method: String) -> Bool {
methodsCalled.contains(method)
}
private func record(_ string: String) {
methodsCalled.insert(string)
}
}
protocol VisitDelegate {
func visitDidStart()
func visitDidComplete()
}
class Visitor {
private let delegate: VisitDelegate
init(delegate: VisitDelegate) {
self.delegate = delegate
}
func visit(_ path: String) {
delegate.visitDidStart()
// Do the visiting.
delegate.visitDidComplete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment