Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value passed to completion handler for unit testing

I'm trying to get the value passed to a completion handler to test against for unit testing. It is not a normal setup for a completion handler since the completion handler is a var:

 typealias ResultType = Result<Data>
    typealias CompletionType = (ResultType) -> ()

 var onCompletion: CompletionType// this is the completion handler

open override func finished(_ errors: [NSError]) {
    self.urlSession.invalidateAndCancel()

self.onCompletion(Result.failure(EComError.networkError(.notReachable)))

    }
}

I'm trying to compare the var: onCompletion with the

self.onCompletion(Result.failure(EComError.networkError(.notReachable)))

but when I try and print the var: onCompletion after the function has been it returns:

Optional((Function))

I'm trying to write a test case like this:

   func test_finishedResult(){

        sut?.finished([NSError(code: OperationErrorCode.executionFailed)])
           XCTAssertEqual(sut?.onCompletion(Result.failure(EComError.networkError(.notReachable))), sut?.onCompletion)
    }

but it returns the error:

Cannot convert value of type 'DownloadOperation.CompletionType?' (aka 'Optional<(Result) -> ()>') to expected argument type '()?'

where

DownloadOperation

is the name of the class the function is in.

Whats the best way to unit test the that the var:

onCompletion

is equal toself.onCompletion(Result.failure(EComError.networkError(.notReachable)))?

like image 284
SwiftyJD Avatar asked May 20 '26 02:05

SwiftyJD


1 Answers

With your test code you are not comparing the value passed to the completion, but instead the function pointers of your callbacks.

What you probably want is something like:

   func test_finishedResult() {
        // Set your callback here 
        sut?.onCompletion = { result in 
            // Compare the result here
            XCTAssertEqual(Result.failure(EComError.networkError(.notReachable)), result)
        }
        // Trigger the callback with the finished method
        sut?.finished([NSError(code: OperationErrorCode.executionFailed)])
    }
like image 96
Dejan Skledar Avatar answered May 21 '26 17:05

Dejan Skledar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!