Author : MD TAREQ HASSAN
AutoFixture AutoMoq
- Integrates Moq to Autofixute
- Autofixute uses Moq to mock dependency and feeds test data to test method
Setup
Install-Package AutoFixture.Xunit2
Install-Package AutoFixture.AutoMoq
Note: AutoFixture.AutoMoq
has dependency on Moq, so Nuget will install Moq automatically.
AutoMockData attribute
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute(params object[] values) : base(new Func<IFixture>(() => new Fixture().Customize(new AutoMoqCustomization())))
{
}
}
ProductService.cs
public class ProductService
{
private readonly IDatabase _database;
public ProductService(IDatabase database)
{
_database = database;
}
public IEnumerable<Product> GetAllProducts()
{
return _database.FindAllProduct();;
}
}
Using AutoMock data attribute
Mock<IDatabase>
: provides mocked implementation ofIDatabase
[Frozen]Mock<IDatabase>
: Freezes mocked implementation & injects into ProductService
[Theory, AutoMoqData]
public void Test([Frozen]Mock<IDatabase> database, ProductService sut)
{
// Assert
}
InlineAutoMoqData attribute
InlineAutoMoqDataAttribute.cs
public class InlineAutoMoqDataAttribute : CompositeDataAttribute
{
public InlineAutoMoqDataAttribute(params object[] values) : base(new InlineDataAttribute(values), new InlineAutoMoqDataAttribute())
{
}
}
Using InlineAutoMoqData attribute
[Theory]
[InlineAutoMoqData(1.5)]
[InlineAutoMoqData(1.9)]
public void Test(decimal price, [Frozen]Mock<IDatabase> database, ProductService sut)
{
var results = sut.GetAllProductsUnderPrice(price);
// Assert
}