Is there a Automocker.CreateInstance equivalent in NSubstitute?

264 Views Asked by At

When I need to create an instance of a complex object, such as a large service, with Moq, I can achieve it using the following approach:

     //Mocks and Setups needed 
     var autoMocker = new AutoMocker();
     var service = autoMocker.CreateInstance<Service>();
     service.MethodToTest();
    // Verify

With NSubstitute, I haven't found a similar way to accomplish this. I would prefer to avoid direct constructor instantiation, or setting up a service provider and injecting all dependencies, as it would require considerable effort for each test involving large services.

I manage to come close to a solution using AutoFixture:

    var fixture = new Fixture();
    fixture.Customize( new AutoNSubstituteCustomization());
    var repo = Substitute.For<IRepo>();
    repo.GetById(Arg.Any<int>()).Returns(someObjectOrValue);
    
    var service = fixture.Create<Service>();
    service.MethodToTest();

While this allows me to create an instance of the service and call the method, it appears that none of the "mocks" I created using Substitute.For had any impact inside the MethodToTest(), meaning that the repo.GetById(int id) always returns null.

Does anyone knows a solution or alternative to this scenario?

1

There are 1 best solutions below

0
mu88 On

To be precise: AutoMocker is an extension rather than an essential part of Moq - Moq does not have this ability on its own.

This being said, there is no well-adopted alternative to AutoMocker for NSubstitute. However, what comes closest to it is this package: https://www.nuget.org/packages/NSubstituteAutoMocker
But as you see, it hasn't seen any updates for almost the last decade.

So long story short: unfortunately, I'm not aware of any proper alternative for NSubstitute that is as convenient as AutoMocker.