1

I'm trying to grab a value from a URL inside a XCUI Test. However it's not outputting so I'm not sure if there's anything I'm supposed to be doing aside from I've already tried in the code below:

import XCTest

class ExampleUITests: XCTestCase {


func testExample() {
    print("We are in XCUITest textExample right now")

    let urlString = "https://api.ipify.org/"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }

        guard let data = data
            else {
                print("error found in data")
                return
        }

        print("*******")
        let outputStr  = String(data: data, encoding: String.Encoding.utf8) as String!
        print (outputStr)

        }.resume()

}

}
hnaderi
  • 409
  • 8
  • 16
  • I tried adding in a completion block as mentioned in this question https://stackoverflow.com/questions/40810108/swift-http-request-use-urlsession but it still didn't give me any output – hnaderi Jun 25 '18 at 19:25

1 Answers1

2

The problem is, response from server is returned after test is finished. You should add waiting for network response in the test.

At the start of the test add:

let expectation = expectationWithDescription("")

At the end of the test add:

waitForExpectationsWithTimeout(5.0) { (error) in
    if error != nil {
        XCTFail(error.localizedDescription)
    }
}

And in the network completion block add:

expectation.fulfill()

You can get more info about waining for async task in the test for example here How can I get XCTest to wait for async calls in setUp before tests are run?.

Kryštof Matěj
  • 462
  • 3
  • 16