Writing unit tests for AppIntent with a @AppDependency declared

I am trying to write a unit test for an AppIntent and override the AppDependencyManager so I can inject dependencies for the purposes of testing. When I run a test, the app crashes with:

AppIntents/AppDependencyManager.swift:120: Fatal error: AppDependency  of type Int.Type was not initialized prior to access. Dependency values can only be accessed inside of the intent perform flow and within types conforming to _SupportsAppDependencies unless the value of the dependency is manually set prior to access.

App Intent:

import AppIntents

struct TestAppIntent: AppIntent {
  @AppDependency var count: Int
  
  static var title: LocalizedStringResource { "Test App Intent "}
    
  func perform() async throws -> some IntentResult {
    print("\(count)")
    
    return .result()
  }
}

extension TestAppIntent {
  init(dependencyManager: AppDependencyManager) {
    _count = AppDependency(manager: dependencyManager)
  }
}

Unit Test

import Testing
import AppIntents
@testable import AppIntentTesting

struct TestAppIntentTests {
  @Test("test")
  func test() async throws {
    let dependencyManager = AppDependencyManager()
    dependencyManager.add(dependency: 5)
    
    let appIntent = TestAppIntent(dependencyManager: dependencyManager)
    _ = try await appIntent.perform()
  }
}

Just figured this out. Here's how to create an instance of your app intent with a custom dependency manager:

    let dependencyManager = AppDependencyManager()
    dependencyManager.add(dependency: 5)
    let appIntent = TestAppIntent(count: .init(manager: dependencyManager))
    let _ = try await appIntent.resolveAndPerform()

Your way with an extension should work too, but is unnecessary if your code can access the intent type's default .init() method.

You have to use .resolveAndPerform() to get the dependency injection to happen, .perform() alone doesn't do it.

Writing unit tests for AppIntent with a @AppDependency declared
 
 
Q