An auto-mocking container for NSubstitute — the NSubstitute flavor of Moq.AutoMocker.
Construct the class under test and let the container automatically generate substitutes for any dependencies you have not explicitly supplied.
dotnet add package AutoMocker.NSubstitute
The library types live in the NSubstitute.AutoMock namespace.
var mocker = new AutoMocker();
// Creates CarFactory with substitutes for all constructor dependencies
CarFactory carFactory = mocker.CreateInstance<CarFactory>();
// Configure a dependency using regular NSubstitute syntax
mocker.GetSubstitute<IEngineProvider>()
.GetEngine()
.Returns(new Engine());
// Provide explicit instances when needed
mocker.Use<IColorPicker>(new RedColorPicker());
Car car = carFactory.Create();
// Verify using regular NSubstitute syntax
mocker.GetSubstitute<IEngineProvider>().Received(1).GetEngine();CreateInstance<T>()— constructsT, resolving constructor arguments from the container or generating substitutes.GetSubstitute<T>()— retrieves (or creates) the substitute used for a service, ready to be configured withReturns,Received, etc.Use(...)/With(...)— register explicit instances, factories, or implementation types.CreateSelfSubstitute<T>()/WithSelfSubstitute<T>()— partial substitutes (Substitute.ForPartsOf) so you can test a class while substituting selected virtual members.Combine(...)— one substitute instance registered under multiple service types.- Built-in resolution of
IEnumerable<T>, arrays,Lazy<T>,Func<T>, andCancellationTokendependencies. AsDisposable()— dispose all disposable instances tracked by the container.- Implements
IServiceProvider.
The package ships with source generators (ported from Moq.AutoMocker) that light up automatically:
- Constructor null-argument tests — decorate a partial test class with
[ConstructorTests(TargetType = typeof(MyClass))]and unit tests assertingArgumentNullExceptionfor each constructor parameter are generated for MSTest, NUnit, xUnit, or TUnit. WithOptions<T>()— generated whenMicrosoft.Extensions.Optionsis referenced; wires up the options pattern services.WithFakeLogging()— generated whenMicrosoft.Extensions.Diagnostics.Testingis referenced; resolvesILogger/ILogger<T>/ILoggerFactorywithFakeLogger.WithFakeTimeProvider()— generated whenMicrosoft.Extensions.TimeProvider.Testingis referenced.WithKeyedService(...)— generated whenMicrosoft.Extensions.DependencyInjection.Abstractions8+ is referenced.WithMeterFactory()— generated whenSystem.Diagnostics.DiagnosticSource10+ is referenced.WithApplicationInsights()— generated whenMicrosoft.ApplicationInsightsis referenced.
Each generator can be disabled with an MSBuild property, e.g. <EnableAutoMockerNSubstituteOptionsGenerator>false</EnableAutoMockerNSubstituteOptionsGenerator>.
See the source generator docs for detailed usage, examples, and troubleshooting for each generator.