Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在swift中测试缓存响应?_Ios_Swift_Caching_Urlsession - Fatal编程技术网

Ios 如何在swift中测试缓存响应?

Ios 如何在swift中测试缓存响应?,ios,swift,caching,urlsession,Ios,Swift,Caching,Urlsession,我正在尝试为swift中的URLSession缓存编写单元测试 有没有办法知道响应是来自服务器还是来自缓存,这样我就可以编写单元测试来检查我的响应是否被缓存?您需要将URLCache子类化以创建一个模拟并配置URLSession,以便它使用您的MockURLCache 您的MockURLCache覆盖: override func getCachedResponse(for dataTask: URLSessionDataTask, completionHandler: @escaping (C

我正在尝试为swift中的
URLSession
缓存编写单元测试


有没有办法知道响应是来自服务器还是来自缓存,这样我就可以编写单元测试来检查我的响应是否被缓存?

您需要将URLCache子类化以创建一个模拟并配置URLSession,以便它使用您的MockURLCache

您的MockURLCache覆盖:

override func getCachedResponse(for dataTask: URLSessionDataTask, completionHandler: @escaping (CachedURLResponse?) -> Void) {
    super.getCachedResponse(for: dataTask) { cachedURLResponse in
        self.retrievedCachedResponse?(cachedURLResponse) 
        completionHandler(cachedURLResponse)
    }
}
其中,
self.retrievedCachedResponse(:)
是一个可选的闭包类型:

class MockURLCache: URLCache {
    var retrievedCachedResponse: ((CachedURLResponse?) -> Void)?
    ...
}

可以方便地在单元测试中设置。然后,此闭包可能会实现您可以断言的XTestExpection。

您需要将URLCache子类化以创建一个模拟并配置URLSession,以便它使用您的MockURLCache

您的MockURLCache覆盖:

override func getCachedResponse(for dataTask: URLSessionDataTask, completionHandler: @escaping (CachedURLResponse?) -> Void) {
    super.getCachedResponse(for: dataTask) { cachedURLResponse in
        self.retrievedCachedResponse?(cachedURLResponse) 
        completionHandler(cachedURLResponse)
    }
}
其中,
self.retrievedCachedResponse(:)
是一个可选的闭包类型:

class MockURLCache: URLCache {
    var retrievedCachedResponse: ((CachedURLResponse?) -> Void)?
    ...
}
可以方便地在单元测试中设置。然后,此闭包可能会满足您可以断言的XctestExpection。

不确定为什么要这样做。我可以想象,您想要测试自己的网络库,这可能是有意义的。如果您想测试API,URLCaching是一个底层细节,IMHO不应该在API测试中进行测试。此外,是否缓存响应还取决于响应和缓存控制响应头-这由后端决定,通常也不可在单元测试(可能是集成测试)中测试,但最好在后端测试中完成。不确定为什么要这样做。我可以想象,您想要测试自己的网络库,这可能是有意义的。如果您想测试API,URLCaching是一个底层细节,IMHO不应该在API测试中进行测试。此外,是否缓存响应还取决于响应和缓存控制响应头—这由后端决定,通常也不可在单元测试(可能是集成测试)中测试,但最好在后端测试中完成。