Skip to content

Instantly share code, notes, and snippets.

@helje5
Created August 17, 2023 16:19
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save helje5/dfaafc29fc0e081756fadfacc7b0076a to your computer and use it in GitHub Desktop.
Save helje5/dfaafc29fc0e081756fadfacc7b0076a to your computer and use it in GitHub Desktop.
Unit Testing a SwiftUI Query
//
// Created by Helge Heß.
// Copyright © 2023 ZeeZide GmbH.
//
import XCTest
import UIKit
import SwiftData
import SwiftUI
class SwiftUITestCase: XCTestCase {
private lazy var window : UIWindow? = {
let window = UIWindow(frame: .init(x: 0, y: 0, width: 720, height: 480))
window.isHidden = false
return window
}()
func constructView<V: View>(_ view: V,
waitingFor expectation: XCTestExpectation) throws
{
let window = try XCTUnwrap(self.window)
window.rootViewController = UIHostingController(rootView: view)
window.rootViewController?.view.layoutIfNeeded()
wait(for: [expectation], timeout: 2)
}
}
final class SwiftQueryTests: SwiftUITestCase {
@Model
final class Item {
var name : String
init(name: String) { self.name = name }
}
private let context : ModelContext? = {
guard let container = try? ModelContainer(
for: Item.self,
ModelConfiguration(inMemory: true)
) else { return nil }
let context = ModelContext(container)
context.insert(Item(name: "One"))
context.insert(Item(name: "Two"))
context.insert(Item(name: "Three"))
return context
}()
func testFetchCount() throws {
let context = try XCTUnwrap(context)
class TestResults {
var fetchedCount = 0
}
struct TestView: View {
let results : TestResults
let expectation : XCTestExpectation
@Query var values : [ Item ]
var body: Text { // This must NOT be an `EmptyView`!
results.fetchedCount = values.count
expectation.fulfill()
return Text(verbatim: "Dummy")
}
}
let expectation = XCTestExpectation(description: "Test Query Count")
let results = TestResults()
let view = TestView(results: results, expectation: expectation)
.modelContext(context)
try constructView(view, waitingFor: expectation)
#if false // this crashes the 15b6 compiler
XCTAssertEqual(results.fetchedCount, 3)
#else
XCTAssertTrue(results.fetchedCount == 3)
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment