我们正在使用 Swift 2.x(最新)并想要BDD(单元测试)我们的代码.另外,我们也使用 RxSwift.我们的重写方法不会在我们的自定义测试存根中调用.我们的代码: protocol SomethingDeliverable { func fetch
protocol SomethingDeliverable { func fetchSomething(somethingId: String, associatedList: String) -> Observable<String> } extension SomethingDeliverable { func fetchSomething(somethingId: String, associatedList: String) -> Observable<String> { return create { observer in return NopDisposable.instance } } }
为了测试,我们有这个测试代码:
private class StubSomethingApi: SomethingDeliverable { var responseClosure: ((AnyObserver<String>) -> Void)? func fetchSomething(somethingId: String, associatedList: String) -> Observable<String> { return create { observer in if let responseClosure = self.responseClosure { responseClosure(observer) } return NopDisposable.instance } } }
我们希望返回Observable< T>而不是返回Observable< String>的fetchSomething.并让StubSomethingAPI成功覆盖它以测试sakes.
我们怎么做?
protocol SomethingDeliverable { associatedtype Element func fetchSomething(somethingId: String, associatedList: String) -> Observable<Element> } extension SomethingDeliverable { func fetchSomething(somethingId: String, associatedList: String) -> Observable<Element> { return create { observer in return NopDisposable.instance } } } private class StubSomethingApi<T>: SomethingDeliverable { typealias Element = T var responseClosure: ((AnyObserver<T>) -> Void)? func fetchSomething(somethingId: String, associatedList: String) -> Observable<T> { return create { observer in if let responseClosure = self.responseClosure { responseClosure(observer) } return NopDisposable.instance } } }