Skip to content

Testing trait not behaving as expected #321

@DavidvanErkelens

Description

@DavidvanErkelens

Hi there! I'm trying to build a test using the .container Suite macro, but it seems like when I run my tests in parallel the same instance of a dependency is used in multiple tests. I have a test like this:

import Factory
import FactoryTesting
import Testing

@Suite(.container)
struct MyTests {
    @Test()
    func testOne() async {
        let actorDouble = MyActorTestDouble()
        Container.shared.myActor.register { actorDouble }

        let viewModel = MyViewModel()

        await viewModel.run()

        #expect(await actorDouble.invoked == 1) // expectation failed, invoked == 2
    }

    @Test()
    func testTwo() async {
        let actorDouble = MyActorTestDouble()
        Container.shared.myActor.register { actorDouble }

        let viewModel = MyViewModel()

        await viewModel.run()

        #expect(await actorDouble.invoked == 1) // expectation failed, invoked == 0
    }
}

// Protocol for a background process
public protocol MyProtocol: Actor {
    func run()
}

// Actual implementation
public actor MyActor: MyProtocol {
    public func run() {
        // actual logic
    }
}

// Test double
public actor MyActorTestDouble: MyProtocol {
    public var invoked: Int = 0

    public func run() {
        invoked += 1
    }
}

extension Container {
    public var myActor: Factory<MyProtocol> {
        self { MyActor() }
    }
}

// View model invoking background process
@MainActor
class MyViewModel {
    @Injected(\.myActor) private var myActor: MyProtocol

    func run() async {
        await myActor.run()
    }
}

I would expect both tests to succeed here, but the only way I get them to succeed is either to run them individually or by adding .serialized to the @Suite macro. Is there anything I'm missing setting up these tests, or is the .container macro behaving differently than expected?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions