Swift_Testing
Swift Testing
Intro
New framework by apple which would be more expressive and is more aligned with what apple has started pushing for swift concurrency manifesto + macros in recent years.
For me it seems like a first party / class citizen treatment finally from apple to its testing framework tools.
Code
Renames
Test Throws
#expect(throws: URLParserPlayerError.self) {
try urlResolver.isTemplateValid(resolverInput)
}
#expect {
try urlResolver.isTemplateValid(resolverInput)
}
throws: { error in
if let errorParsed = error as? URLParserPlayerError {
#expect(errorParsed != nil)
#expect(errorDescription == errorParsed.description)
}
}
Problems
How to Wait
wait(for:timeout:)
Combine
Combine reactive paradigm testing with expectations to confirmation
@Test
func imageRetrieved() async {
var cancellable: AnyCancellable?
await confirmation { imageRetrieved in
cancellable = viewModel.$image.dropFirst().sink { _ in
// Do nothing on completion.
} receiveValue: {
#expect($0 != nil)
imageRetrieved()
}
}
cancellable?.cancel()
}
Converted to use AsyncSequence
on the publishers
@Test
func imageRetrieved() async {
let value = await viewModel.$image.values.first()
#expect(value != nil)
}
With this extension to simplify the call to first(where:)
:
extension AsyncSequence {
func first() async rethrows -> Element? {
try await first(where: { _ in true})
}
}
Reference
swift with majid | swift testing basics