Last active
October 7, 2022 11:31
-
-
Save damodarnamala/8d9428516bafd18573348adac194d991 to your computer and use it in GitHub Desktop.
Testing aync `combine` code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol DollarRateUseCase { | |
func fetchDollarRate() -> AnyPublisher<Int, Never> | |
} | |
struct DollarRateUseCaseTask: DollarRateUseCase { | |
func fetchDollarRate() -> AnyPublisher<Int, Never> { | |
return Future { promise in | |
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { | |
promise(.success(83)) | |
} | |
}.eraseToAnyPublisher() | |
} | |
} | |
struct DollarRateUseCaseMockTask: DollarRateUseCase { | |
func fetchDollarRate() -> AnyPublisher<Int, Never> { | |
return Just<Int>(80) .eraseToAnyPublisher() | |
} | |
} | |
class ViewModel { | |
var useCase: DollarRateUseCase | |
init(useCase: DollarRateUseCase = DollarRateUseCaseTask()) { | |
self.useCase = useCase | |
} | |
func fetch() -> AnyPublisher<Int, Never> { | |
return useCase.fetchDollarRate() | |
} | |
} | |
// Testing | |
final class TestDollarRateSpec: XCTestCase { | |
let viewModel = ViewModel(useCase: DollarRateUseCaseMockTask()) | |
var cancellable = Set<AnyCancellable>() | |
func testFetchingDollarRate() { | |
let exp = expectation(description: "await completion") | |
viewModel.fetch().sink { value in | |
XCTAssertTrue(value == 80, "Getting failed to replicate mock dollar rate ") | |
exp.fulfill() | |
}.store(in: &cancellable) | |
wait(for: [exp], timeout: 2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment