'Swift Async/Await testing crashes in unit test
there is a LocationRepo class that gets a CoreDataWorker injected. This class has a function fetchAllLocations that exectues a get on the worker to retrieve data.
So far, so good - the worker's get function and the worker itself are under test and working without problems.
However, when calling the fetchAllLocations function from a test, then the test hangs first, before crashing with this message:
Message from debugger: Terminated due to signal 9
Program ended with exit code: 9
The SUT:
public class LocationRepo: LocationRepository {
let worker: CoreDataWorkerProtocol
private var currentLocation: Location?
public init(worker: CoreDataWorkerProtocol = CoreDataWorker()) {
self.worker = worker
}
public func fetchAllLocations() async -> Result<[Location], Error> {
debugPrint(self.worker)
let result: Result<[Location], Error> = await worker.get(
with: nil,
sortDescriptors: nil,
fetchLimit: nil
)
switch result {
case .success(let locations):
return .success(locations)
case .failure(let error):
debugPrint(error)
return .failure(error)
}
}
...
}
The unit test:
class LocationRepoTests: XCTestCase {
func testLocationRepo_fetchAll() async throws {
Resolver.reset()
Resolver.registerPersistence(persistenceServiceEnvironment: .previews)
let persistenceService: PersistenceService = Resolver.resolve()
let worker = CoreDataWorker(persistenceService: persistenceService)
let repo = LocationRepo(worker: worker)
let result = await repo.fetchAllLocations()
switch result {
case .success(let list):
XCTAssertTrue(list.isEmpty)
default:
XCTFail("Unexpected result")
}
}
}
Calling the content of the fetchAllLocations function from the test works fine.
So: Why does that wrapping function fetchAllLocations lead to crash? Is it a bug in Xcode, or am I doing something wrong?
Solution 1:[1]
I noticed a continuously increasing memory usage during the "hanging" phase of the crash. This lead me on the right track: There was a protocol extension that was triggered by the LocationRepo's "get" call, that caused a recursion. However, what is strange, is that this situation did not happen when the call itself was put directly into the unit test. So, I fixed the problem, but I don't understand why it occurs in one situation, and not in another...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hardy |
