ios - XCTestCase Multipart params with Alamofire utilizing URLProtocolStub in Swift - Slsolutech Best IT Related Website, pub-5682244022170090, DIRECT, f08c47fec0942fa0

ios – XCTestCase Multipart params with Alamofire utilizing URLProtocolStub in Swift

Spread the love

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

My situation is that after I obtain a response, I get the URLRequest and I examine the httpBody for getting my params. Sadly it’s nil and I don’t know one other option to get multipartData.

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

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

last class URLProtocolStub: URLProtocol {
    personal struct Stub {
        let information: Knowledge?
        let response: URLResponse?
        let error: Error?
        let requestObserver: ((URLRequest) -> Void)?
    personal static var _stub: Stub?
    personal static var stub: Stub? {
        get { return queue.sync { _stub } }
        set { queue.sync { _stub = newValue } }
    personal static let queue = DispatchQueue(label: "URLProtocolStub.queue")
    static func stub(information: Knowledge?, response: URLResponse?, error: Error?) {
        stub = Stub(information: information, response: response, error: error, requestObserver: nil)
    static func observeRequests(observer: @escaping (URLRequest) -> Void) {
        stub = Stub(information: 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 information = stub.information {
            shopper?.urlProtocol(self, didLoad: information)
        if let response = stub.response {
            shopper?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        if let error = stub.error {
            shopper?.urlProtocol(self, didFailWithError: error)
        } else {

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

let configuration =
configuration.protocolClasses = [URLProtocolStub.self] 

Lastly, my check perform for testing HTTP request with multipart information.

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(information: 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(information: $0, encoding: .utf8) }, "firstname=mock&lastname=check")

        // 3
        let consequence = await makeSUT(loggerDelegate: loggerDelegate).requestMultipart(imageDatas: [imageData], pathType: anyPathType(.put up, bodyParameters: bodyParams, urlParameters: nil))

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

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

I clarify this perform step-by-step :

  1. I put together my bodyParams & picture for my multipart request.
  2. I create a listener for hear HTTP response when acquired.
  3. And I create my AlamofireHTTPClient (makeSUT perform) 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 suitable 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 tips on how to get my multipart params to check it :(.

Thanks for serving to me :).

Leave a Reply

Your email address will not be published. Required fields are marked *