Applying a new Assembly from UI test doesn't change returned instance

54 views Asked by At

I try to change a registered protocol from UI test but it doesn't change. What I am doing wrong here?
I have a shared DIAssembler that manage dependancies using Assemblies as following:

import Swinject

class DIAssembler {
    static let shared = DIAssembler()

    var container: Container
    private let assembler: Assembler

    init() {
        self.container = Container()
        assembler = Assembler(container: container)
        assembler.apply(assembly: ProductionAssembly())

        let processInfo = ProcessInfo.processInfo
        if processInfo.isUITesting {
            let keys = processInfo[.assemblyKeys] ?? ""
            assembler.apply(assembly: TestAssembly(keys: keys))
        }
    }

    #if Debug
    public func apply(_ assembly: Assembly) {
        assembler.apply(assembly: assembly)
    }
    #endif
}

Production and Test Assembly have same structure, I only change the created instance

class ProductionAssembly: Assembly {

    func assemble(container: Container) {
        registerPaymentRequests(container)
    }
    private func registerPaymentRequests(_ container: Container) {
        container.register(PaymentApiClientProtocol.self) { _ in
            PaymentsApiClient()
        }
    }
}

Sometimes I want to change returned instance from the DI after an action happen.. so I try applying a new Assembly to change registered instance but it always returns the previous instance PaymentsApiClient instead of TestingPaymentsApiClient

DIAssembler.shared.apply(FromUITestAssembly())

class FromUITestAssembly: Assembly {
    func assemble(container: Container) {
        container.register(PaymentApiClientProtocol.self) { _ in
            return TestingPaymentsApiClient()
        }
    }
}
0

There are 0 answers