Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/moq/Moq.AutoMocker

An auto-mocking IoC container for Moq
https://github.com/moq/Moq.AutoMocker

hacktoberfest

Last synced: about 1 month ago
JSON representation

An auto-mocking IoC container for Moq

Awesome Lists containing this project

README

        

# Moq.AutoMock ![Continuous](https://github.com/moq/Moq.AutoMocker/workflows/Continuous/badge.svg) [![NuGet Status](https://img.shields.io/nuget/v/Moq.AutoMock.svg?style=flat)](https://www.nuget.org/packages/Moq.AutoMock)

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.

```csharp
var mocker = new AutoMocker();
var car = mocker.CreateInstance();

car.DriveTrain.ShouldNotBeNull();
car.DriveTrain.ShouldImplement();
Mock 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().Use(x)` in StructureMap).

```csharp
var mocker = new AutoMocker();

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

var car = mocker.CreateInstance();
```

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.

```csharp
var mocker = new AutoMocker();

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

var car = mocker.CreateInstance();
car.Accelerate(42);

// Then extract & verify
var driveTrainMock = mocker.GetMock();
driveTrainMock.VerifyAll();
```

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

```csharp
var mocker = new AutoMocker();
mocker.Use(x => x.Accelerate(42) == true);

var car = mocker.CreateInstance();
car.Accelerate(42);

// This method verifies all mocks in the container
mocker.VerifyAll();
```