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?