Author : MD TAREQ HASSAN

AutoFixture AutoMoq

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

[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
}