Skip to content

Instantly share code, notes, and snippets.

@al-76
Created January 15, 2023 22:01
Show Gist options
  • Save al-76/1f803dc3d1f3e606a94a3c1de825d851 to your computer and use it in GitHub Desktop.
Save al-76/1f803dc3d1f3e606a94a3c1de825d851 to your computer and use it in GitHub Desktop.
//
// XCTestCase+Await.swift
//
// Useful functions to test with Combine
//
import Combine
import XCTest
enum TestAwaitError: Error {
case unexpectedResult
}
extension XCTestCase {
func values<T: Publisher>(_ publisher: T) async throws -> [T.Output] {
var result: [T.Output] = []
for try await value in publisher.values {
result.append(value)
}
return result
}
func value<T: Publisher>(_ publisher: T) async throws -> T.Output? {
(try await values(publisher)).first
}
func error<T: Publisher>(_ publisher: T) async -> T.Failure where T.Failure == Error {
do {
_ = try await values(publisher)
} catch let error {
return error
}
return TestAwaitError.unexpectedResult
}
}
//
// For example, we want to test some Use Case with fake Repository that returns Combine AnyPublisher
//
//@MainActor
//final class SearchDocumentUseCaseTests: XCTestCase {
// private var repository: FakeDocumentsRepository!
// private var useCase: SearchDocumentUseCase!
//
// override func setUp() async throws {
// repository = FakeDocumentsRepository()
// useCase = SearchDocumentUseCase(repository: repository)
// }
//
// func testExecute() async throws {
// // Arrange
// repository.readAnswer = Answer.success(.stub)
//
// // Act
// let result = try await value(useCase(with: "test"))
//
// // Assert
// XCTAssertEqual(result, .stub)
// }
//
// func testExecuteError() async {
// // Arrange
// repository.readAnswer = Answer.fail()
//
// // Act
// let result = await error(useCase(with: "test"))
//
// // Assert
// XCTAssertEqual(result as? TestError, .someError)
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment