// Example of mocking network layer in Swift
import SwiftUI
import Combine
// Define a protocol for the network service
protocol NetworkService {
func fetchData() -> AnyPublisher
}
// Implement a real network service
class RealNetworkService: NetworkService {
func fetchData() -> AnyPublisher {
// Actual network call logic here
// ...
}
}
// Create a mock network service for testing
class MockNetworkService: NetworkService {
func fetchData() -> AnyPublisher {
// Provide a mocked response
let sampleData = Data("Sample response data".utf8)
return Just(sampleData)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
// A ViewModel that uses the NetworkService
class ViewModel: ObservableObject {
@Published var data: Data?
private var cancellables = Set()
let networkService: NetworkService
init(networkService: NetworkService) {
self.networkService = networkService
}
func loadData() {
networkService.fetchData()
.sink(receiveCompletion: { _ in }, receiveValue: { [weak self] data in
self?.data = data
})
.store(in: &cancellables)
}
}
// SwiftUI View using the ViewModel
struct ContentView: View {
@StateObject private var viewModel: ViewModel
init(viewModel: ViewModel) {
_viewModel = StateObject(wrappedValue: viewModel)
}
var body: some View {
// Your view code here using viewModel.data
Text("Your UI here")
}
}
// Usage in testing
let mockService = MockNetworkService()
let viewModel = ViewModel(networkService: mockService)
viewModel.loadData()
// Assert the output or UI behavior in tests
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?