DevTeam / Pure.DI

Pure DI for .NET
MIT License
410 stars 21 forks source link

Overriding bindings from test project #56

Closed psyren89 closed 1 month ago

psyren89 commented 2 months ago

In a regular ASP.NET project, for example, you can set up your DI via Startup.cs:

services.AddSingleton<IServiceA, ServiceA>()
  .AddSingleton<IServiceB, ServiceB>();

and in the test project, you can do this to override the configured DI for the main project (see here):

builder.ConfigureTestServices(services => services.AddSingleton<IServiceA, MockServiceA>());

Is there a way to do something similar with this library? I have tried the following: Main project (has no knowledge of test project):

// Composition.cs
public partial class Composition;

// Startup.cs
DI.Setup("Namespace.Composition").Bind<IServiceA>().As(Lifetime.Singleton).To<ServiceA>().Root<IServiceA>();

Test project (references main project):

// BaseTest.cs
DI.Setup("Namespace.Composition")
  .Bind<IServiceA>().As(Lifetime.Singleton).To(_ => Mock.Of<IServiceA>).Root<IServiceA>();

Inspecting the Composition instance and stepping through the code during debugging shows that the test setup isn't overriding the original as I'd like. Is there an approach I should use?

NikolayPianikov commented 1 month ago

I've added sample tests in this repository.

Pure.DI is not a DI container, but a source code generator. All code is generated at compile time. It's the same with tests. In the example you will find integration tests, I guess your question is more related to them.

This example generates a test composition based on settings from the Lib library:

private void Setup() =>
  DI.Setup(nameof(MyServiceTests))
    // Based on the Composition setup from the Lib namespace
    .DependsOn("Lib.Composition")
    // Overrides some instances using mocks
    .Bind<IOutput>().To(_ => _output.Object)
    .Bind<IInput>().To(_ => _input.Object)
    // Exposing a test instance as the composition root 
    .Root<IService>("Service");

In the test composition, some of the objects are replaced by Mocks. And the test object is defined as the root of the composition.