Does this test make proper use of AutoFixture and Moq? Is it written as concisely as possible? The test fails, as expected, and passes after writing the correct implementation.
[Fact]
public void CustomerPropertyIsCorrect()
{
var fixture = new AutoMoqFixture();
var expected = fixture.Create<CardHolderCustomer>();
var builderMock = fixture
.Freeze<Mock<ICustomerAdapter>>()
.Setup(x => x.BuildCustomer()).Returns(expected);
var sut = fixture.Create<CardHolderViewModel>();
var actual = sut.Customer;
Assert.Equal(expected, actual);
}
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. 1. var fixture = new Fixture(); 2.
AutoFixture is a tool designed to make Test-Driven Development more productive and unit tests more refactoring-safe.
It's looking good! However, you can also use it declaratively with the xUnit.net extension.
Assuming that the types used in the test are defined as:
public class CardHolderCustomer
{
}
public interface ICustomerAdapter
{
CardHolderCustomer BuildCustomer();
}
public class CardHolderViewModel
{
private readonly ICustomerAdapter adapter;
public CardHolderViewModel(ICustomerAdapter adapter)
{
if (adapter == null)
throw new ArgumentNullException("adapter");
this.adapter = adapter;
}
public CardHolderCustomer Customer
{
get
{
return this.adapter.BuildCustomer();
}
}
}
The original test can be written as:
[Theory, DomainTestConventions]
public void CustomerPropertyIsCorrect2(
CardHolderCustomer expected,
[Frozen]Mock<ICustomerAdapter> builderStub,
CardHolderViewModel sut)
{
builderStub
.Setup(x => x.BuildCustomer())
.Returns(expected);
var actual = sut.Customer;
Assert.Equal(expected, actual);
}
The DomainTestConventionsAttribute
is defined as:
internal class DomainTestConventionsAttribute : AutoDataAttribute
{
internal DomainTestConventionsAttribute()
:base(new Fixture().Customize(new DomainTestConventions()))
{
}
}
The DomainTestConventions
is defined as:
internal class DomainTestConventions : CompositeCustomization
{
internal DomainTestConventions()
:base(new AutoMoqCustomization())
{
}
}
Note that DomainTestConventions
derives from CompositeCustomization
which basically means that you can create more Customizations and add them as parameters to the base constructor.
You may also read:
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With