Issues with setUp() and tearDown() in XCTest for Swift 6

Hello! I'm working on migration a project to Swift 6 and encountering the following error in tests: "Call to main actor-isolated initializer 'init(viewModel:)' in a synchronous nonisolated context".

final class MicOnboardingViewTests: XCTestCase, @unchecked Sendable {
    var sut: UIViewController!
    var presenter: MicOnboardingPresenter!
    
    override func setUp() {
        super.setUp()
        
         // ...

        // ERROR: Call to main actor-isolated initializer 'init(viewModel: viewModel)' in a synchronous nonisolated context
        presenter = MicOnboardingPresenter(viewModel: viewModel)
    }
    
    // ...
}

The issue is that I have a Presenter class that conforms to the MicOnboardingPresentationLogic protocol, which is marked as @MainActor and Sendable:

@MainActor
protocol MicOnboardingPresentationLogic: Sendable {
    func presentFetchedData(model: MicOnboardingModels.FetchData)
}

final class MicOnboardingPresenter: MicOnboardingPresentationLogic {
    // MARK: - Properties

    private var viewModel: MicOnboardingViewModel

    // MARK: - Initialization

    init(viewModel: MicOnboardingViewModel) {
        self.viewModel = viewModel
    }

    // MARK: - MicOnboardingPresentationLogic

    func presentFetchedData(model: MicOnboardingModels.FetchData) {
        // .. //
    }
}

I understand that the issue is due to setUp() and tearDown() being synchronous in a nonisolated context.

My question is: how should cases like this be handled when I have an entity marked as MainActor and I need to create it in the setUp() of the test? Currently, all tests are broken, and I don’t yet know a suitable solution for this situation.

3 Likes

You can mark the test case as @MainActor which I think is the way to go for this use case