Skip to content

Instantly share code, notes, and snippets.

View Kdan's full-sized avatar

Kewin Remeczki Kdan

  • Copenhagen, Denmark
View GitHub Profile
/// The base class for all mock classes.
class Mock: MockType {
/// The log containing function call information.
let log = FunctionLogger()
}
protocol MockType {
/// The log storing function calls.
var log: FunctionLogger { get }
}
extension MockType {
/// A Bool indicating if the class has received any function calls.
var hasReceivedCalls: Bool { log.hasReceivedCalls }
/// Retrieve the potential calls for a given function name.
/// A `FunctionCall` corresponds to the trigger of a function.
struct FunctionCall: Hashable {
/// The name of the function
let name: String
/// The parameters sent to the function.
let parameters: [Any?]
/// The number of times the function has been called.
let calls: Int
static func == (lhs: FunctionCall, rhs: FunctionCall) -> Bool {
typealias FunctionName = String
class FunctionLogger<T: RawRepresentable> where T.RawValue == FunctionName {
/// A flag indicating if the class has received any function calls.
var hasReceivedCalls: Bool { !functionCalls.isEmpty }
/// The function calls.
private var functionCalls: [T.RawValue: FunctionCall] = .init()
/// Retrieve the potential calls for a given function name.
/// - Parameters:
/// The name of a function, used to look up calls on the `Mock` class.
protocol FunctionName {
/// The raw value of the function name.
var rawValue: String { get }
}
class ConcreteBTests: XCTestCase {
/// The testable `B` class.
private var b: ConcreteB!
/// The mocked `C` class injected to `b`.
private var c: CMock!
override func setUp() {
super.setUp()
c = CMock()
b = ConcreteB(c: c)
class ATests: XCTestCase {
/// The testable `A` class.
private var a: A!
/// The mocked `B` class injected to `a`.
private var b: BMock!
override func setUp() {
super.setUp()
b = BMock()
a = A(b: b)
class BMock: B {
/// The mocked response being returned by the `validateAnswer()` function.
var validateAnswerResponse = true
func validateAnswer() -> Bool { validateAnswerResponse }
}
class CMock: C {
/// Mutable variable can be changed during the test.
var number = 42
class A {
/// A `Bool` indicating if we have the answer to the universe.
private(set) var hasAnswer = false
/// The instance of B we are using to check if we have the answer.
private let b: B
init(b: B) {
self.b = b
}
class A {
/// A `Bool` indicating if we have the answer to the universe.
private(set) var hasAnswer = false
/// The instance of B we are using to check if we have the answer.
private let b: B
init(b: B) {
self.b = b
}