Skip to content
An auto-mocking IoC container for Moq
C#
Branch: master
Clone or download
ascott18 and Keboo Include xmldoc comments in Nuget packages (#62)
* Won't pack on dotnet\sdk\3.0.100-preview4-011223 due to NU5030
... "error NU5030: The license file 'LICENSE' does not exist in the package."

Changed according to the example at https://docs.microsoft.com/en-us/nuget/reference/errors-and-warnings/nu5030

* Include xmldoc comments for better Intellisense experience.

I had to suppress CS1591 from triggering errors, since there's plenty of members (approx 40) that don't have xmldoc comments. I'll leave this as future work to someone more well suited to documenting these.
Latest commit e4809bd May 18, 2019

README.md

Moq.AutoMock Build statusNuGet Status

An automocking container for Moq. Use this if you're invested in your IoC container and want to decouple your unit tests from changes to their constructor arguments.

Usage

Simplest usage is to build an instance that you can unit test.

var mocker = new AutoMocker();
var car = mocker.CreateInstance<Car>();

car.DriveTrain.ShouldNotBeNull();
car.DriveTrain.ShouldImplement<IDriveTrain>();
Mock<IDriveTrain> mock = Mock.Get(car.DriveTrain);

If you have a special instance that you need to use, you can register it with .Use(...). This is very similar to registrations in a regular IoC container (i.e. For<IService>().Use(x) in StructureMap).

var mocker = new AutoMocker();

mocker.Use<IDriveTrain>(new DriveTrain());
// OR, setup a Mock
mocker.Use<IDriveTrain>(x => x.Shaft.Length == 5);

var car = mocker.CreateInstance<Car>();

Extracting Mocks

At some point you might need to get to a mock that was auto-generated. For this, use the .Get<>() or .GetMock<>() methods.

var mocker = new AutoMocker();

// Let's say you have a setup that needs verifying
mocker.Use<IDriveTrain>(x => x.Accelerate(42) == true);

var car = mocker.CreateInstance<Car>();
car.Accelerate(42);

// Then extract & verify
var driveTrainMock = mocker.GetMock<IDriveTrain>();
driveTrainMock.VerifyAll();

Alternately, there's an even faster way to verify all mocks in the container:

var mocker = new AutoMocker();
mocker.Use<IDriveTrain>(x => x.Accelerate(42) == true);

var car = mocker.CreateInstance<Car>();
car.Accelerate(42);

// This method verifies all mocks in the container
mocker.VerifyAll();
You can’t perform that action at this time.