我的单元测试随机通过/失败
func test_WhenRequestHasURLParams_CorrectlyEncodesParams() {
sut.call(endpoint: MockEndpoint.endpointOne(paramOne: "foo", paramTwo: "bar")) { (response: MockResponse) in }
XCTAssertEqual(mockURLSession.urlComponents?.percentEncodedQuery, "keyOne=4Plus5%3DNine&keyTwo=foo")
}
之所以发生这种情况,是因为我在运行测试时percentEncodedQuery
的顺序不断变化。
我有一个编码器,用于创建请求对象,在这种情况下,它是
public struct URLParameterEncoder: ParameterEncoder {
public static func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {
guard let url = urlRequest.url else { throw NetworkError.missingURL }
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
urlComponents.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key,value: "\(value)")
urlComponents.queryItems?.append(queryItem)
}
urlRequest.url = urlComponents.url
}
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
}
}
public typealias Parameters = [String: Any]
public protocol ParameterEncoder {
static func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws
}
public enum ParameterEncoding {
case urlEncoding, jsonEncoding, urlAndJsonEncoding
public func encode(urlRequest: inout URLRequest, bodyParams: Parameters?, urlParams: Parameters?) throws {
do {
switch self {
case .urlEncoding:
guard let urlParams = urlParams else { return }
try URLParameterEncoder.encode(urlRequest: &urlRequest, with: urlParams)
case .jsonEncoding:
guard let bodyParams = bodyParams else { return }
try JSONParameterEncoder.encode(urlRequest: &urlRequest, with: bodyParams)
case .urlAndJsonEncoding:
guard let bodyParams = bodyParams, let urlParams = urlParams else { return }
try URLParameterEncoder.encode(urlRequest: &urlRequest, with: urlParams)
try JSONParameterEncoder.encode(urlRequest: &urlRequest, with: bodyParams)
}
} catch {
throw NSError(domain: "Could not encode request", code: 0, userInfo: nil)
}
}
}
我不知道为什么订单会不断变化