How Can I Return `nil` for HTTPURLResponse?

323 Views Asked by At

I have the following method which I used for retrieving a cookie from response headers:

internal static func cookie(from response: HTTPURLResponse) -> HTTPCookie? {
    guard let url = response.url else { return nil }
    guard let headerFields = response.allHeaderFields as? HTTPHeaders else { return nil }
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
    for cookie in cookies {
        if cookie.name == "connect.sid" { return cookie }
    }
    return nil
}

I am creating unit tests to verify that my code returns nil for appropriate scenarios. However, the only part of the above method that I cannot seem to test effectively is:

guard let url = response.url else { return nil }

In my test, I create a response to pass into the above method:

guard let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: responseHeaders) else { fatalError("Invalid response") }

Since the initializer for HTTPURLResponse requires a non-optional URL, I can't seem to figure out how to test the response with a nil value for its url property.

Is there a way for me to test this with a nil url?

1

There are 1 best solutions below

0
On

By using the HTTPURLResponse() initializer instead of passing parameters, I was able to have a nil value for the response's url property.