Last active
January 18, 2025 22:45
-
-
Save colinfwren/b9207703184533d56f1fcc738a7074b3 to your computer and use it in GitHub Desktop.
Unit tests for service
This file contains hidden or 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
import Testing | |
import Foundation | |
import SwiftData | |
@testable import ExampleApp | |
@Suite("Example Service Test") struct ExampleServiceTest { | |
let someOtherModelDescriptor = FetchDescriptor<SomeOtherModel>(sortBy: [SortDescriptor(\SomeOtherModel.created, order: .reverse)]) | |
@MainActor @Test("Adding SomeModel record when have SomeOtherModel record") func addRecordWithExisting() throws { | |
// setup | |
let config = ModelConfiguration(isStoredInMemoryOnly: true) | |
let container = try ModelContainer(for: SomeOtherModel.self, SomeModel.self, configurations: config) | |
let service = ExampleService(modelContext: container.mainContext) | |
// Create SomeOtherModel record | |
let someOtherRecord = SomeOtherModel(name: "Foo") | |
container.mainContext.insert(someOtherRecord) | |
// Check no existing SomeModel records before calling function | |
service.fetchData() | |
#expect(service.someList.count == 0) | |
// Call function and check it's set everything up correctly | |
service.someComplexMultiModelAction() | |
#expect(service.someList.count == 1) | |
let otherModelRecords = try container.mainContext.fetch(someOtherModelDescriptor) | |
#expect(otherModelRecords.count == 1) | |
#expect(service.someList.first.otherModelInstance == otherModelRecords.first) | |
} | |
@MainActor @Test("Adding SomeModel record when no SomeOtherModel record") func addRecordNoExisting() throws { | |
// setup | |
let config = ModelConfiguration(isStoredInMemoryOnly: true) | |
let container = try ModelContainer(for: SomeOtherModel.self, SomeModel.self, configurations: config) | |
let service = ExampleService(modelContext: container.mainContext) | |
// Check no existing SomeOtherModel records before calling function | |
let otherModelRecordsBefore = try container.mainContext.fetch(someOtherModelDescriptor) | |
#expect(otherModelRecordsBefore.count == 0) | |
// Check no existing SomeModel records before calling function | |
service.fetchData() | |
#expect(service.someList.count == 0) | |
// Call function and check it's set everything up correctly | |
service.someComplexMultiModelAction() | |
#expect(service.someList.count == 1) | |
let otherModelRecordsAfter = try container.mainContext.fetch(someOtherModelDescriptor) | |
#expect(otherModelRecordsAfter.count == 1) | |
#expect(service.someList.first.otherModelInstance == otherModelRecordsAfter.first) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment