Skip to content

Instantly share code, notes, and snippets.

@al-76
Last active January 15, 2023 22:03
Show Gist options
  • Save al-76/01296d4fcbcb0aafa710de6a0637a066 to your computer and use it in GitHub Desktop.
Save al-76/01296d4fcbcb0aafa710de6a0637a066 to your computer and use it in GitHub Desktop.
//
// Answer.swift
//
// Answer is useful for testing to avoid boilerplate code
//
enum TestError: Error {
case someError
}
enum Answer {
static func success<T>(_ data: T) -> AnyPublisher<T, Error> {
Just(data)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
static func fail<T>(_ error: Error = TestError.someError) -> AnyPublisher<T, Error> {
Fail<T, Error>(error: error)
.eraseToAnyPublisher()
}
static func fail<T>(_ error: Error, _ type: T.Type) -> AnyPublisher<T, Error> {
Fail<T, Error>(error: error)
.eraseToAnyPublisher()
}
static func nothing<T>() -> AnyPublisher<T, Error> {
Empty<T, Error>()
.eraseToAnyPublisher()
}
}
// For example:
//
// 1. We have a fake implementation for testing purpose with answer AnyPublisher
// final class FakeSearchHistoryUseCase: UseCase {
// var answer = Answer.success([History].stub)
//
// func callAsFunction(with query: String) -> AnyPublisher<[History], Error> {
// answer
// }
//}
//
// 2. Then we could use Answer.success() (as well as error(), nothing())
// func testHistorySearch() {
// // Arrange
// searchHistoryUseCase.answer = Answer.success(.stub)
// // Act
// viewModel.searchHistory = "test"
// // Assert
// XCTAssertEqual(viewModel.history, .stub)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment