artyom.razinov
artyom.razinov

Reputation: 665

iOS unit tests: how to handle completion of tests?

I want to write path of test artifacts at the end of output in console. It would be handy. And I'm also just curious.

It seems that XCTest somehow terminate the app, app delegate doesn't receive lifecycle callbacks, program exits before main function from main.m.

Upvotes: 2

Views: 939

Answers (3)

kuzdu
kuzdu

Reputation: 7524

For me the answers were very confusing.

func testYourTest() {
 let expectation = XCTestExpectation(description: "Your action")

 API.sharedInstance.yourRequestWithCompletionAndFailure(parameter: parameter, completion: { (response) in

 //XCTAssert with response

 expectation.fulfill()
 }) { (error) in
  //XCTAssert with your error
 expectation.fulfill()
 }

 wait(for: [expectation], timeout: 30.0)
}

With expectation you listen to a response. Don't forget to set a timeout. More Details/Source: https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations

Upvotes: 1

artyom.razinov
artyom.razinov

Reputation: 665

Jonah helped me, I also want to place some code here for other people.

To start observation before any test there is a proper way to do it. There is NSPrincipalClass key in test bundle's Info.plist. Put there a name of your "principal class" (google it for more info). In my case it is PrincipalClass. When test bundle is loaded, init is called in the principal class. Here's my PrincipalClass:

@objc(PrincipalClass)
final class PrincipalClass: NSObject {
    override init() {
        TestObservationEntryPoint.instance.startObservation()
    }
}

I was able to make cool reporting system with Allure2. Reporting is not what I wanted at the time I asked this question, but it was possible because I found an answer. It is a good application of test observation in XCTest.

Upvotes: 3

Jonah
Jonah

Reputation: 17958

Take a look at Test Execution and Observation specifically testBundleDidFinish.

If you define an object which adopts XCTestObservation you can add it to the XCTestObservationCenter.shared instance at any point during your test suite's run and receive a call when the entire bundle has finished.

Upvotes: 3

Related Questions