Skip to content

Instantly share code, notes, and snippets.

@rinold
Created July 17, 2018 09:36
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 rinold/3b9c28ebf80420bdf468ad29ce0ccaeb to your computer and use it in GitHub Desktop.
Save rinold/3b9c28ebf80420bdf468ad29ce0ccaeb to your computer and use it in GitHub Desktop.
import XCTest
protocol ApiForMocking {
func testFunc1()
func testFunc2()
func testFunc3()
}
class ApiMock: ApiForMocking {
enum Methods: String {
case testFunc1
case testFunc2
case testFunc3
}
var calls: [Methods] = []
func testFunc1() {
calls.append(.testFunc1)
}
func testFunc2() {
calls.append(.testFunc2)
}
func testFunc3() {
calls.append(.testFunc3)
}
}
class ServiceUnderTest {
let api: ApiForMocking
init(api: ApiForMocking) {
self.api = api
}
func someMethod() {
api.testFunc1()
api.testFunc3()
}
}
class ExampleTests: XCTestCase {
func testSomeMethod() {
// Given
let mockApi = ApiMock()
let service = ServiceUnderTest(api: mockApi)
// When
service.someMethod()
// Then
XCTAssert(mockApi.calls == [.testFunc1, .testFunc3])
// The above check automatically verifies following:
// - Both testFunc1 and testFunc3 are called and called once
// - Order of calls
// - No other calls were done
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment