我在 Swift 5 專案中使用 MockingBird 進行模擬。像這樣的測驗可以通過:
// In app
protocol SomeProtocol {
func getNumber() -> Int
}
// In tests
import Mockingbird
import XCTest
@testable import MyApp
class Test: XCTestCase {
func testExample() throws {
let mock: SomeProtocolMock! = mock(SomeProtocol.self)
given(mock.getNumber()).willReturn(1)
_ = mock.getNumber() as Int
}
}
但是,如果我添加一個型別引數,它就不起作用:
// In app
protocol SomeProtocol {
func getNumber<T>(_ type: T.Type) -> Int
}
// In tests
import Mockingbird
import XCTest
@testable import MyApp
class Test: XCTestCase {
func testExample() throws {
let mock: SomeProtocolMock! = mock(SomeProtocol.self)
given(mock.getNumber(Int.self)).willReturn(1)
_ = mock.getNumber(Int.self) as Int
}
}
運行后一個測驗會出現以下錯誤:
缺少帶有引數 [Int (by reference)] 的 'getNumber(_ type: T.Type) -> Int' 的存根實作
確保該方法具有使用回傳型別注冊的具體存根或默認值提供程式。
示例:
given(someMock.getNumber(...)).willReturn(someValue)
given(someMock.getNumber(...)).will { return someValue }
someMock.useDefaultValues(from: .standardProvider)
為什么這不起作用?有什么辦法可以解決這個問題,例如使用any()?
uj5u.com熱心網友回復:
我想我知道問題所在。
將引數更改為any() as Int.Type。
測驗檔案如下所示:
// In tests
import Mockingbird
import XCTest
@testable import MyApp
class Test: XCTestCase {
func testExample() throws {
let mock: SomeProtocolMock! = mock(SomeProtocol.self)
given(mock.getNumber(any() as Int.Type)).willReturn(1)
_ = mock.getNumber(Int.self) as Int
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452926.html
