Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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