Using mocks for unit testing makes it easy to write test cases without configuring actual dependencies. However, it is hard to manually write and update all the mocking classes whenever there is a change. Here, Sourcery can help generate them automatically with a command.
protocol CounterDelegate: AnyObject {
func counter(_ counter: Counter, didUpdateCount count: Int)
}
class Counter {
weak var delegate: CounterDelegate?
private(set) var count = 0 {
didSet { delegate?.counter(self, didUpdateCount: count) }
}
func increment() {
count += 1
}
}
@testable import Tracker
import XCTest
final class CounterTests: XCTestCase {
private var counter: Counter!
override func setUp() {
super.setUp()
counter = Counter()
}
func testIncrement() {
counter.increment()
XCTAssertEqual(counter.count, 1)
}
}
// sourcery: AutoMockable
protocol CounterDelegate: AnyObject {
func counter(_ counter: Counter, didUpdateCount count: Int)
}
sourcery --sources <sources path> --templates <templates path> --output <output path>
class CounterDelegateMock: CounterDelegate {
//MARK: - counter
var counterDidUpdateCountCallsCount = 0
var counterDidUpdateCountCalled: Bool {
return counterDidUpdateCountCallsCount > 0
}
var counterDidUpdateCountReceivedArguments: (counter: Counter, count: Int)?
var counterDidUpdateCountReceivedInvocations: [(counter: Counter, count: Int)] = []
var counterDidUpdateCountClosure: ((Counter, Int) -> Void)?
func counter(_ counter: Counter, didUpdateCount count: Int) {
counterDidUpdateCountCallsCount += 1
counterDidUpdateCountReceivedArguments = (counter: counter, count: count)
counterDidUpdateCountReceivedInvocations.append((counter: counter, count: count))
counterDidUpdateCountClosure?(counter, count)
}
}
@testable import Tracker
import XCTest
final class CounterTests: XCTestCase {
private var delegate: CounterDelegateMock!
private var counter: Counter!
override func setUp() {
super.setUp()
delegate = CounterDelegateMock()
counter = Counter()
counter.delegate = delegate
}
func testIncrement() {
counter.increment()
XCTAssertEqual(counter.count, 1)
// Assert counter(_:, didUpdateCount:) is called
XCTAssertTrue(delegate.counterDidUpdateCountCalled)
// Assert received count parameter to be 1
XCTAssertEqual(delegate.counterDidUpdateCountReceivedArguments?.count, 1)
}
}
Looking for a new challenge? Join Our Team
From us to your inbox weekly.