问题描述
如何模拟URLSession.DataTaskPublisher
?我有一个需要注入URLSessionProtocol
How can I mock URLSession.DataTaskPublisher
? I have a class Proxy
that require to inject a URLSessionProtocol
protocol URLSessionProtocol {
func loadData(from url: URL) -> URLSession.DataTaskPublisher
}
class Proxy {
private let urlSession: URLSessionProtocol
init(urlSession: URLSessionProtocol) {
self.urlSession = urlSession
}
func get(url: URL) -> AnyPublisher<Data, ProxyError> {
// Using urlSession.loadData(from: url)
}
}
此代码最初与带有完成处理程序的URLSession
的传统版本一起使用.这是完美的,因为我可以在此处轻松模拟URLSession
以进行类似Sundell的解决方案的测试:模拟在Swift 中.
This code was originally used with the traditional version of URLSession
with the completion handler. It was perfect since I could easily mock URLSession
for testing like Sundell's solution here: Mocking in Swift.
是否可以对Combine Framework进行相同的操作?
Is it possible to do the same with the Combine Framework?
推荐答案
与注入URLSessionProtocol
来模拟具体会话的方式相同,也可以注入模拟的Publisher
.例如:
In the same way that you can inject a URLSessionProtocol
to mock a concrete session, you can also inject a mocked Publisher
. For example:
let mockPublisher = Just(MockData()).eraseToAnyPublisher()
但是,取决于您对这个发布者的处理方式,您可能需要解决与Combine async出版者的某些怪异之处,请参阅此帖子以进行其他讨论:
However, depending on what you do with this publisher you might have to address some weirdnesses with Combine async publishers, see this post for additional discussion:
为什么Combine的receive(on :)运算符会误入错误?
这篇关于如何模拟URLSession.DataTaskPublisher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!