kingLitrV
kingLitrV

Reputation: 33

Unit test with Swift: body of closure not executed

There are functions that send a request to server, get response and print result. They always work in the iOS app itself but only sometimes (looks like randomly) in unit-tests of this app.

Main issue: Xcode doesn't enter the body of a closure in unit-tests, just skips it.

Any ideas how can it be fixed? Image of the problem in Xcode.

Upvotes: 3

Views: 3826

Answers (1)

mokagio
mokagio

Reputation: 17481

The most likely reason because the completion closure of your requests are not being exectued is that they are performing an asynchronous operation, while the tests run synchronously. This means that the test finishes running while your network request is still processing.

Try using XCTestExpectation:

func testIt() {
  let expectation = expectationWithDescription("foobar")

  // request setup code here...

  Alamofire.request(.POST, "...")
    .responseJSON { response in
      //
      // Insert the test assertions here, for example:
      //
      if let JSON = response.result.value as? [String: AnyObject] {
        XCTAssertEqual(JSON["id"], "1")
      } else {
        XCTFail("Unexpected response")
      }

      //
      // Remember to call this at the end of the closure
      //
      expectation.fulfill()
  }

  //
  // This will make XCTest wait for up to 10 seconds,
  // giving your request expectation time to fulfill
  //
  waitForExpectationsWithTimeout(10) { error 
    if let error = error {
      XCTFail("Error: \(error.localizedDescription)")
    }
  }
}

Upvotes: 11

Related Questions