How to write a test that expects a method call using swift and XCTest?
I could use OCMock, but they don't officially support swift, so not much of an option.
As you said OCMock does not support Swift(nor OCMockito), so for now the only way I see is to create a hand rolled mock. In swift this is a little bit less painful since you can create inner classes within a method, but still is not as handy as a mocking framework.
Here you have an example. The code is self explanatory, the only thing I had to do(see EDIT 1 below) to make it work is to declare the classes and methods I want to use from the test as public(seems that the test classes do not belong to the same application's code module - will try to find a solution to this).
EDIT 1 2016/4/27: Declaring the classes you want test as public is not necessary anymore since you can use the "@testable import ModuleName" feature.
The test:
import XCTest
import SwiftMockingPoC
class MyClassTests: XCTestCase {
func test__myMethod() {
// prepare
class MyServiceMock : MyService {
var doSomethingWasCalled = false
override func doSomething(){
doSomethingWasCalled = true
}
}
let myServiceMock = MyServiceMock()
let sut = MyClass(myService: myServiceMock)
// test
sut.myMethod()
// verify
XCTAssertTrue(myServiceMock.doSomethingWasCalled)
}
}
MyClass.swift
public class MyClass {
let myService: MyService
public init(myService: MyService) {
self.myService = myService
}
public func myMethod() {
myService.doSomething()
}
}
MyService.swift
public class MyService {
public init() {
}
public func doSomething() {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With