Skip to content

Instantly share code, notes, and snippets.

@polac24
Last active March 31, 2019 18:05
Show Gist options
  • Save polac24/8606fdaebdb0e6680d9c86d2bb004634 to your computer and use it in GitHub Desktop.
Save polac24/8606fdaebdb0e6680d9c86d2bb004634 to your computer and use it in GitHub Desktop.
// Globally defined helper function that injects a spy
// to record all stub function calls along with their arguments
func spyCalls<I,O>(of stub: inout (I) -> (O)) -> (ArgRecords<I>) {
// data structure to track all args
let argRecords = ArgRecords<I>()
// keep previously used stub function
let orginalStub = stub
// override stub implementation (inout stub argument)
stub = { [weak weakArgRecords = argRecords] i in
weakArgRecords?.record(i) // store arg to the data structure
return orginalStub(i) // call original body implementation
}
return argRecords
}
// Stub declaraion
class DatabaseStub: Database {
lazy var addUserAction = niceStub(of: addUser)
func addUser(name: String) -> Bool {
return addUserAction(name)
}
}
// Sample testcase
func testAddingUser_savesToDatabase() {
// Arrange - introduce addUser's spy
let addUserArgs = spyCalls(&database.addUserAction)
// Act
database.addUser(name: "myuser") // returns defaultly `false`
// Assert
XCTAssertEqual(addUserArgs[0], "myuser") // ✅
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment