HomeiOS Developmentios - XCTestCase Multipart params with Alamofire utilizing URLProtocolStub in Swift

ios – XCTestCase Multipart params with Alamofire utilizing URLProtocolStub in Swift


I want to know the way can I check multipart sending params with Alamofire (community stack). Ex: ship a string with a picture (Information sort).

My subject is that once I obtain a response, I get the URLRequest and I verify the httpBody for getting my params. Sadly it’s nil and I don’t know one other technique to get multipartData.

(I’ve already do some search earlier than asking right here ;))

For Doing this, I create a stub URLProtocol (referred to as URLProtocolStub)

closing class URLProtocolStub: URLProtocol {
    non-public struct Stub {
        let knowledge: Information?
        let response: URLResponse?
        let error: Error?
        let requestObserver: ((URLRequest) -> Void)?
    }
    
    non-public static var _stub: Stub?
    non-public static var stub: Stub? {
        get { return queue.sync { _stub } }
        set { queue.sync { _stub = newValue } }
    }
    
    non-public static let queue = DispatchQueue(label: "URLProtocolStub.queue")
    
    static func stub(knowledge: Information?, response: URLResponse?, error: Error?) {
        stub = Stub(knowledge: knowledge, response: response, error: error, requestObserver: nil)
    }
    
    static func observeRequests(observer: @escaping (URLRequest) -> Void) {
        stub = Stub(knowledge: nil, response: nil, error: nil, requestObserver: observer)
    }
    
    override class func canInit(with request: URLRequest) -> Bool {
        return true
    }
    
    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }
    
    override func startLoading() {
        guard let stub = URLProtocolStub.stub else { return }
        
        if let knowledge = stub.knowledge {
            shopper?.urlProtocol(self, didLoad: knowledge)
        }
        
        if let response = stub.response {
            shopper?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        }
        
        if let error = stub.error {
            shopper?.urlProtocol(self, didFailWithError: error)
        } else {
            shopper?.urlProtocolDidFinishLoading(self)
        }
        
        stub.requestObserver?(request)
    }
}

And I set it on the URLConfigurationSession to be used a faux session on Alamaofire.

let configuration = URLSessionConfiguration.af.ephemeral
configuration.protocolClasses = [URLProtocolStub.self] 

Lastly, my check operate for testing HTTP request with multipart knowledge.

func test_uploadMultipart_with_params() async {
        // 1
        let httpURL = HTTPURLResponse(statusCode: 204)
        let bodyParams = ["firstname": "mock", "lastname": "test"]
        let imageData = UIColor.yellow.picture(CGSize(width: 128, peak: 128)).jpegData(compressionQuality: 0.7)

        URLProtocolStub.stub(knowledge: nil, response: httpURL, error: nil)

        let exp = expectation(description: "Ready to obtain response")

        // 2
        let loggerDelegate = StubHTTPLoggerDelegate(didReceivedResponse: { request in
            XCTAssertEqual(request?.httpBody.flatMap { String(knowledge: $0, encoding: .utf8) }, "firstname=mock&lastname=check")
            exp.fulfill()
        })

        // 3
        let end result = await makeSUT(loggerDelegate: loggerDelegate).requestMultipart(imageDatas: [imageData], pathType: anyPathType(.publish, bodyParameters: bodyParams, urlParameters: nil))

        do { attempt end result.get() } catch { XCTFail("(error)") }

        wait(for: [exp], timeout: 1.0)
    }

I clarify this operate step-by-step :

  1. I put together my bodyParams & picture for my multipart request.
  2. I create a listener for hear HTTP response when obtained.
  3. And I create my AlamofireHTTPClient (makeSUT operate) by passing my listener and name my Alamorefire requestMultipart with my bodyParams & picture. Then a execute my shopper.

My check is checking if I’m sending the appropriate parameters on a Alamofire multipart request.
This check failed as a result of the httpBody from a request (URLRequest) is nil and I do not know methods to get my multipart params to check it :(.

Thanks for serving to me :).

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments