Mocking and stubbing are crucial techniques in SwiftUI development for unit testing. They allow developers to isolate components, simulate behavior, and ensure that the code works as expected without relying on external systems. Mocking involves creating a fake implementation of a class or protocol that mimics the original behavior, while stubbing is used to simulate specific responses from dependencies.
// Protocol defining the service
protocol DataService {
func fetchData() -> String
}
// Mock class implementing the service
class MockDataService: DataService {
func fetchData() -> String {
return "Mock Data"
}
}
// Your view model that uses the DataService
class ViewModel: ObservableObject {
@Published var data: String = ""
var dataService: DataService
init(dataService: DataService) {
self.dataService = dataService
}
func loadData() {
data = dataService.fetchData()
}
}
// Example usage in SwiftUI View
struct ContentView: View {
@StateObject var viewModel: ViewModel
var body: some View {
Text(viewModel.data)
.onAppear {
viewModel.loadData()
}
}
}
// Test case using the MockDataService
func testViewModel() {
let mockService = MockDataService()
let viewModel = ViewModel(dataService: mockService)
viewModel.loadData()
assert(viewModel.data == "Mock Data")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?