How can I skip XCTest if the close is not called?

I have the following unit test:

let apiService = FreeApiService(httpClient: httpClient)
apiService.connect() {(status, error) in
     XCTAssertTrue(status)
     XCTAssertNil(error)
}

The actual function is as follows:

typealias freeConnectCompleteClosure = ( _ status: Bool, _ error: ApiServiceError?)->Void

class FreeApiService : FreeApiServiceProtocol {
    func connect(complete: @escaping freeConnectCompleteClosure) {
       ...
       case 200:
            print("200 OK")
            complete(true, nil)
    }
}

This unit test passes, but the problem is that if I forget the part complete(true, nil), the test will pass anyway. I cannot find a way to make my test fail by default if the close is not called.

What am I missing?

+4
source share
2 answers

For this you need to use XCTTestExpectation. This will skip the test if it is not explicitly executed.

, expectation(description:) . fulfill() . , connect() XCTestCase "wait", waitForExpectations(timeout:). , , .

Apple " " doc.

+2

, FreeApiService. , ( ), FreeApiService . , .

  • -
  • ,

, (- ) (- ), . :

func testConnect_ShouldCallCompletionHandlerWithTrueStatusAndNilError() {
    let apiService = FreeApiService(httpClient: httpClient)
    var capturedStatus: Bool?
    var capturedError: Error?

    let promise = expectation(description: "Completion handler invoked")
    apiService.connect() {(status, error) in
        capturedStatus = status
        capturedError = error
        promise.fulfill()
    }
    waitForExpectations(timeout: 5, handler: nil)

    XCTAssertTrue(capturedStatus ?? false, "status")
    XCTAssertNil(capturedError, "error")
}

, waitForExpectations 5 . .

. , , , :

  • ,

.

... ! . , , . . . , , . , :

  • ? .
  • ? .

, , , . .

+1

Source: https://habr.com/ru/post/1695020/


All Articles