Search code examples
swiftxcodeunit-testingxcode-extension

How to test XCSourceEditorCommandInvocation for Xcode Extension?


I'm trying to add tests for my Xcode Source Editor extension. Ideally I'd like to use the system classes from XcodeKit, allowing me to test the whole system, but I don't seem to be able to create a XCSourceEditorCommandInvocation.

Is there a way to get around this to test my extension? Here's an example of what I want:

import Testing
import XcodeKit
@testable import TestingToolsExtension

struct TestingToolsTests {
    @Test func example() async throws {
        let invocation = XCSourceEditorCommandInvocation() // How to initialise?
        
        let sut = SourceEditorCommand()
        sut.perform(with: invocation, completionHandler: { _ in })
        
        // Verify different outputs
    }
}

Solution

  • You can use the fact that XCSourceEditorCommandInvocation inherits from NSObject:

    if let instance = (XCSourceEditorCommandInvocation.self as NSObject.Type).init() as? XCSourceEditorCommandInvocation {
        print("Instance created: \(instance)")
    } else {
        print("Failed to create instance")
    }
    

    But this only makes sense when you don't do anything with the instance and just passing it to make the method call