Testing Combine code example
Example: Testing Combine
class CarViewModelTest: XCTestCase {
var car: Car!
var carViewModel: CarViewModel!
var cancellables: Set<AnyCancellable>!
override func setUp() {
car = Car()
carViewModel = CarViewModel(car: car)
cancellables = []
}
func testCarViewModelEmitsCorrectStrings() {
let newValue: Double = car.kwhInBattery - car.kwhPerKilometer * 10
var expectedValues = [car.kwhInBattery, newValue].map { doubleValue in
return "The car now has \(doubleValue)kwh in its battery"
}
let receivedAllValues = expectation(description: "all values received")
carViewModel.batterySubject.sink(receiveValue: { value in
guard let expectedValue = expectedValues.first else {
XCTFail("Received more values than expected.")
return
}
guard expectedValue == value else {
XCTFail("Expected received value \(value) to match first expected value \(expectedValue)")
return
}
expectedValues = Array(expectedValues.dropFirst())
if expectedValues.isEmpty {
receivedAllValues.fulfill()
}
}).store(in: &cancellables)
carViewModel.drive(kilometers: 10)
waitForExpectations(timeout: 1, handler: nil)
}
}