Learning to Unit Test The Observable Macro
No more Combine! Observable FTW
5 min readSep 5, 2024
During WWDC 2023 Apple swift developers had the opportunity to learn about the shiny new Observation Framework.
That means we no longer need to test @Published
properties to maintain full test coverage. That’s quite nice isn’t it?
Unit Testing With Combine
I have simple project that takes an endpoint (https://jsonplaceholder.typicode.com/posts) and displays them on the screen. There’s a simple viewModel to move the network call out of the view, and a simple service in order to use dependency injection for URLSession
.
It’s 80 lines of code.
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
ScrollView {
LazyVStack{
ForEach(viewModel.posts) { post in
Text(post.title)
}
}
}
.onAppear {
viewModel.getPosts()
}
.alert(
"Login failed.",
isPresented: Binding(get: { viewModel.error != nil }, set: { _,_ in viewModel.error = nil })
) {
Button("OK") {
// TODO: retry mechanism
}
} message: {…