How do I unit test view models in SwiftUI with Swift?

Unit testing view models in SwiftUI is essential to ensure that the business logic operates as expected. By leveraging Swift's powerful testing framework, we can write unit tests that verify the behavior of our view models with different inputs and states.

import SwiftUI import XCTest // Example ViewModel class CounterViewModel: ObservableObject { @Published var count: Int = 0 func increment() { count += 1 } func decrement() { count -= 1 } } // Unit Tests class CounterViewModelTests: XCTestCase { var viewModel: CounterViewModel! override func setUp() { super.setUp() viewModel = CounterViewModel() } func testIncrement() { viewModel.increment() XCTAssertEqual(viewModel.count, 1) } func testDecrement() { viewModel.increment() viewModel.decrement() XCTAssertEqual(viewModel.count, 0) } }

keyword1 keyword2 keyword3