![](/img/trans.png)
[英]Is it possible to mock a method(with parameters) call in XCTest unit test case in IOS
[英]Swift: XCTest delegate/protocol call backs (Unit test)
我需要為委托/協議回調創建一些單元測試。 以下是我要測試的實現示例:
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)來測試委托響應。
我真的很感謝你的幫助。
您可以使用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()
}
}
通過引入Xcode 6的期望 ,異步測試變得更加容易。 期望是由XCTestCase
上的輔助方法創建的,例如:
func expectation(description: String) -> XCTestExpectation
創建並返回與測試用例相關的期望。
更新 。 對於那些運行Xcode 9的人來說,現在這是等待給定XCTestExpectation
實例的首選習慣用法(即代替舊的waitForExpectations
方法):
wait(for: [numbersExpectation], timeout: 100)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.