WeTransfer / Mocker

Mock Alamofire and URLSession requests without touching your code implementation
MIT License
1.1k stars 96 forks source link

How to Mock POST request which have a response ? #110

Closed nik6018 closed 2 years ago

nik6018 commented 2 years ago

Hi,

I have a login API where it accepts values in it's POST body and returns a User Object if the request is successful. I tried multiple ways but I am not able to mock this type of request. I checked Tests file which has many examples, but the example with POST request ignores the response.

Network Mocking is fairly new to me and I am still learning so should I be mocking such a scenario or is this irrelevant ?

I am trying to use the following code

func testUserLogin() {

    let configuration = URLSessionConfiguration.af.default
    configuration.protocolClasses = [MockingURLProtocol.self] + (configuration.protocolClasses ?? [])
    let sessionManager = Session(configuration: configuration)

    let url = URL(string: "https://example.com/login")!
    let validPostBodyExpectation = expectation(description: "Post body was valid")
    let validPostResponse = expectation(description: "Post response was valid")

    let rawPostData: [String: String] = [
        "key1" : "value1",
        "key2" : "value2"
    ]

    let mockedData = try! JSONEncoder().encode(rawPostData)
    let mockedResponseObject = UserDetailMockedData().getMockedObject()

    var mock = Mock(url: url, dataType: .json, statusCode: 200, data: [.post: mockedData])

    mock.onRequest = { request, httpBodyArguments in

        /// Verify the POST arguments
        XCTAssertEqual(httpBodyArguments as? [String: String], [
                "key1" : "value1",
                "key2" : "value2"
        ])

        validPostBodyExpectation.fulfill()
    }

    mock.register()

    sessionManager
        .request(url)
        .responseDecodable(of: UserDetail.self) { (response) in
            XCTAssertNil(response.error)
            XCTAssertEqual(response.value, mockedResponseObject)

            validPostResponse.fulfill()
        }.resume()

    wait(for: [validPostBodyExpectation, validPostResponse], timeout: 10.0)
}
github-actions[bot] commented 2 years ago

This issue is stale because it has been open for 30 days with no activity. Remove the Stale label or comment or this will be closed in 10 days.