Swift:XCTest委托/协议回调(单元测试)

时间:2017-04-26 23:10:08

标签: ios swift xcode delegates xctest

我需要为委托/协议回调创建一些单元测试。以下是我正在尝试测试的实现示例:

protocol SomethingWithNumbersDelegate: class {

    func somethingWithDelegate(results:Int)
}

class SomethingWithNumbers {
    var delegate: SomethingWithNumbersDelegate? = nil
    func doAsyncStuffWithNumbers(number:Int)  {

        var numbers = Int()
        /*
         doing some with the input
         */
        self.delegate?.somethingWithDelegate(results: numbers)
    }
}

我还没有找到创建单元测试(XCTest)来测试委托响应。

我真的很感谢你的帮助。

1 个答案:

答案 0 :(得分:14)

您可以使用XCTestExpectation工具。例如:

class NumbersTest: XCTestCase, SomethingWithNumbersDelegate {

    func testAsynchronousNumbers() {
        numbersExpectation = expectation(description: "Numbers")

        let numbers = SomethingWithNumbers()
        numbers.delegate = self
        numbers.doAsyncStuffWithNumbers(number: 123)

        // Waits 100 seconds for results.
        // Timeout is always treated as a test failure.
        waitForExpectations(timeout: 100)
        XCTAssertEqual(self.results, 456)
    }

    private var numbersExpectation: XCTestExpectation!
    private var results: Int!

    func somethingWithDelegate(results: Int) {
        self.results = results
        numbersExpectation.fulfill()
    }
}

通过引入期望 by Xcode 6,异步测试变得更加容易。期望是由XCTestCase上的辅助方法创建的,例如:

func expectation(description: String) -> XCTestExpectation
  

创建并返回与测试用例相关的期望。

<强>更新即可。对于那些运行Xcode 9的人来说,现在这是等待给定XCTestExpectation实例的首选习惯用法(即代替较旧的waitForExpectations方法):

wait(for: [numbersExpectation], timeout: 100)