MockNetworking 是一个 Swift 包,它通过与 URLProtocol 系统集成,允许重放针对 Apple Networking API 的网络请求的模拟响应。
MockNetworking 可通过 Swift Package Manager 集成到 Xcode 中。在 Xcode 中添加新包时,指向 https://github.com/Machx/MockNetworking.git
。
要设置模拟响应,您只需注册该响应,然后在适当的时候注销该类。在下面的示例中,我们将为 1 个测试设置响应。
let url = try XCTUnwrap(URL(string: "https://wwww.apple.com"))
let response = try XCTUnwrap(HTTPURLResponse(url: url,
statusCode: 200,
httpVersion: HTTPURLResponse.HTTP_1_1,
headerFields: nil))
MockURLProtocol.register(response: response, for: url)
defer {
MockURLProtocol.unregister()
}
这里使用了 HTTPURLResponse
,也提供了一个自定义的 API。
// Swift Test
guard let URL(string: "https://wwww.apple.com"),
let mockResponse = MockPropertyResponse(url: url,
status: 200,
headerFields: [:]) else { throw .couldNotCreateMockResponse }
MockURLProtocol.registerMock(response: mockResponse, for: url)
defer {
MockURLProtocol.unregister()
}
// XCTest
let url = try XCTUnwrap(URL(string: "https://wwww.apple.com"))
let mockResponse = MockPropertyResponse(url: url,
status: 200,
headerFields: [:])
MockURLProtocol.registerMock(response: mockResponse, for: url)
defer {
MockURLProtocol.unregister()
}
register
API 既会将 MockURLProtocol 注册到 URLProtocol 系统(如果尚未注册),也会为给定的 URL 存储预先准备好的响应。
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://apache.ac.cn/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.