Like for NUnit, AutoFixture offers a glue library for Moq.
By using this library, AutoFixture can use Moq to handle the requests for non-concrete types like abstract classes and interfaces. Optionally, AutoFixture can delegate to Moq the creation of fake delegates.
The AutoMoqCustomization is the core of the integration of AutoFixture with Moq. By adding an instance of this class to the fixture, requests for non-concrete types will be handled by Moq.
var fixture =newFixture();fixture.Customize(newAutoMoqCustomization());
The snippets below are based on the following types
[Test]
public void Freezing_is_supported_when_requesting_type()
{
// ARRANGE
fixture.Customize(new AutoMoqCustomization());
var dependency = fixture.Freeze<IDependency>(); // freezing the type directly
// ACT
var sut = fixture.Create<Service>();
// ASSERT
Assert.That(sut.Dependency, Is.SameAs(dependency));
}
[Test]
public void Freezing_is_supported_when_requesting_Mock_of_type()
{
// ARRANGE
fixture.Customize(new AutoMoqCustomization());
var mockDependency = fixture.Freeze<Mock<IDependency>>(); // freezing a mock of the type
// ACT
var sut = fixture.Create<Service>();
// ASSERT
Assert.That(sut.Dependency, Is.SameAs(mockDependency.Object));
}
[Test]
public void AutoMoq_does_not_provide_values_by_default()
{
// ARRANGE
fixture.Customize(new AutoMoqCustomization());
// ACT
var sut = fixture.Create<Service>();
// ASSERT
Assert.That(sut.Dependency, Is.Not.Null);
Assert.That(sut.InnerObject, Is.Not.Null);
Assert.That(sut.InnerObject.StringValue, Is.Null);
}
[Test]
public void AutoMoq_provides_values_if_configured()
{
// ARRANGE
fixture.Customize(new AutoMoqCustomization { ConfigureMembers = true });
// ACT
var sut = fixture.Create<Service>();
// ASSERT
Assert.That(sut.Dependency, Is.Not.Null);
Assert.That(sut.InnerObject, Is.Not.Null);
Assert.That(sut.InnerObject.StringValue, Is.Not.Null);
}
[Test]
public void DoSomething_uses_given_action()
{
// ARRANGE
fixture.Customize(new AutoMoqCustomization { GenerateDelegates = true });
var action = fixture.Create<Action<string>>();
var sut = fixture.Create<Service>();
// ACT
sut.Dependency.DoSomething(action);
// ASSERT
Mock.Get(action).Verify(p => p("Hello world"));
}