Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTest expect method call with swift

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.

like image 419
Rodrigo Ruiz Avatar asked Sep 26 '14 05:09

Rodrigo Ruiz


1 Answers

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() {

    }

}
like image 52
e1985 Avatar answered Oct 04 '22 02:10

e1985