Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing HTTP requests with Mockingjay not working

I am trying to understand how to write UI tests, but I can't seem to get HTTP stubbing to work. When I run the test, I don't see the data from the stub, but the data from the API.

I have tried it in Xcode 10.2 and 9.4.1, so it's not because it no longer works in Xcode 10.

I must be doing something wrong somewhere, but I can't figure out what.

I have created a minimal example to check if it was because I was working in a big project and something was interfering, but that didn't work.

In my viewcontroller I have a simple tableview setup that does an API call, and loads the result into rows. I have a UI testing target that has a simple test setup which uses Mockingjay to stub the HTTP request.

My API call code:

func callSimpleAPI(completionHandler: @escaping ([Patient]?, Error?) -> ()) {
    let url = URL(string: "https://pastebin.com/raw/3PusWbw6")!
    
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        DispatchQueue.main.async {
            guard let data = data else {
                completionHandler(nil, error!)
                return
            }
            
            do {
                let patientResponse = try JSONDecoder().decode(TherapistPatientResponse.self, from: data)
                completionHandler(patientResponse.patients, nil)
            } catch {
                completionHandler(nil, error)
            }
        }
    }
    task.resume()
}

And my testing code:

override func setUp() {
    let app = XCUIApplication()
    app.launch()
    
    stub(everything, json(/*A json representation of the API response that I want to see*/))
}

Edit: I tried this on my iPhone running iOS 12.3 beta and the simulator (not beta).

Edit: Doesn't work with OHHTTPStubs either. Added a branch OHHTTPStubs to the example project.

Edit: I am on macOS Mojave 10.14.3, and I used Xcode 10.2 and 9.4.1 to test. I tried my iPhone running iOS 12.3 and the Simulator running iOS 12.2

like image 553
vrwim Avatar asked Nov 06 '22 19:11

vrwim


1 Answers

You cant stub for UI tests using Mockingjay, since XCUITests run in a different process. You need a library that starts a small http server and responds with your mock. For example https://github.com/httpswift/swifter or https://github.com/envoy/Embassy

like image 177
Marc Armgren Avatar answered Nov 15 '22 08:11

Marc Armgren