import Foundation
import XCTest
class CounterViewModel {
private(set) var count: Int = 0
func increment() {
count += 1
}
func reset() {
count = 0
}
}
final class CounterViewModelTests: XCTestCase {
var viewModel: CounterViewModel!
override func setUp() {
super.setUp()
viewModel = CounterViewModel()
}
override func tearDown() {
viewModel = nil
super.tearDown()
}
func testIncrementIncreasesCount() {
XCTAssertEqual(viewModel.count, 0, "Initial count should be 0")
viewModel.increment()
XCTAssertEqual(viewModel.count, 1, "Count should be 1 after one increment")
viewModel.increment()
XCTAssertEqual(viewModel.count, 2, "Count should be 2 after two increments")
}
func testResetSetsCountToZero() {
viewModel.increment()
XCTAssertEqual(viewModel.count, 1, "Count should be 1 before reset")
viewModel.reset()
XCTAssertEqual(viewModel.count, 0, "Count should be 0 after reset")
}
}
We created a CounterViewModel class with a count property starting at 0. The increment() method adds 1 to count, and reset() sets it back to 0.
We then wrote unit tests using XCTest. The tests check that increment() correctly increases the count and that reset() sets it back to zero. This ensures the ViewModel logic works as expected without any UI.