Search code examples
unit-testingdependency-injectionabp-frameworknsubstitute

ABP - LocalIocManager not found for unit test


In aspnet boilerplate, a LocalIocManager property was available for unit tests to allow to replace a service and then get the instance we wanted to test with only the dependencies required by the test mocked up by NSubstitute.

In abp.io, I cant find this attribute anymore or a replacement procedure. How can I replace it?

In https://docs.abp.io/en/abp/latest/Testing#example-testing-a-domain-service-1, we can see an example with a fakeRepo, but it is injected "by hand". Doing so can be done when there are few dependencies, but become problematic when there are more.


Solution

  • Found a solution: I need to override AfterAddApplication so I have access to IServiceCollection.

    protected override void AfterAddApplication(IServiceCollection services)
    {
        base.AfterAddApplication(services);
    
        var fakeRepo = Substitute.For<IMyRepository>();
        fakeRepo.GetList().Returns(Task.FromResult(new List<Guid>()));
    
        services.Replace(ServiceDescriptor.Transient(typeof(IMyRepository), _ => fakeRepo));
    }
    

    However, this will force me to use the same substitute for all my tests. I can't have different instances for each tests.