Skip to content

Question about using a custom container with a test trait #341

@cassianomonteiro

Description

@cassianomonteiro

I'm looking at the documentation here, but I'm not understanding how to use that custom container to register and get access to my mocks.

For example, my live container is:

extension Container {
  var service: Factory<ServiceProtocol> {
    Factory(self) { ServiceImpl() }.singleton
  }
}

In the live code, I use this to get the instance: Container.shared.service().

I tried to create a custom Container:

public final class TestContainer: SharedContainer {
  @TaskLocal public static var shared = TestContainer()
  public let manager = ContainerManager()
}

extension Trait where Self == ContainerTrait<TestContainer> {
    static var testContainer: ContainerTrait<TestContainer> {
        .init(shared: TestContainer.$shared, container: .init())
    }
}

But then in my test case:

@Suite(.testContainer)
struct CheckoutBackRequestTests {

  @Test
  func myTest async throws {
    let mockService = MockService()
    // How do I register the mock instance?
    TestContainer.shared.service.register { mockService }  // <-- this doesn't work since I don't have a service variable in my TestContainer
    Container.shared.service.register { mockService } // <-- This would be using the regular Container, not the TestContainer, correct?
  }
}

What is the expected usage of a custom container in a test trait?

Thanks in advance!

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