Skip to content

Instantly share code, notes, and snippets.

@thepearl
Created December 12, 2022 00:15
Show Gist options
  • Save thepearl/b010100236664b4d14e1abb109de8a68 to your computer and use it in GitHub Desktop.
Save thepearl/b010100236664b4d14e1abb109de8a68 to your computer and use it in GitHub Desktop.
class MyViewTests: XCTestCase {
func testMyView() throws {
let dataFetcher = MockDataFetcher()
let viewModel = MyViewModel(dataFetcher: dataFetcher)
let view = MyView(viewModel: viewModel)
let window = UIWindow()
window.rootViewController = UIHostingController(rootView: view)
window.makeKeyAndVisible()
let expectation = XCTestExpectation(description: "Fetch data")
dataFetcher.fetchDataResult = "test data"
viewModel.fetchData()
let label = try XCTUnwrap(window.rootViewController?.view.subviews.first as? UILabel)
XCTAssertEqual(label.text, "test data")
expectation.fulfill()
wait(for: [expectation], timeout: 1.0)
}
}
class MockDataFetcher: DataFetcher {
var fetchDataResult: String?
func fetchData() -> AnyPublisher<String, Error> {
if let result = fetchDataResult {
return Result.success(result).publisher
} else {
return Result.failure(MockError.unknown).publisher
}
}
}
enum MockError: Error {
case unknown
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment