Swift Testing Completion Handlers
The author is migrating XCTest cases to Swift Testing, but encountered an issue with testing code that relies on completion handlers. The code uses a custom NSPersistentContainer subclass that loads Core Data stores asynchronously with a completion handler. In XCTest, the author used an expectation mechanism to test the asynchronous operation. The XCTest framework provides a way to create an expectation, mark it as fulfilled, and wait for it to fulfill within a timeout. However, Swift Testing does not use expectations, and its confirmations are not suitable for testing completion handlers. To migrate the test, the author uses a Swift continuation to convert the completion handler call into an async-compatible one. This approach can be used in XCTest as well, removing the need for expectations. The downside of this approach is that failure to call the continuation method can hang the test, and the continuation must be called once and only once. The test can then be easily migrated to Swift Testing by replacing XCTest assertions with #expect. The resulting test uses a Swift continuation to test the asynchronous operation and assert the expected results.