Skip to content

sm-g/AutoFixture.XUnit2.AutoMock

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Objectivity.AutoFixture.XUnit2.AutoMock

Build Status Tests Status codecov License: MIT FOSSA Status

Accelerates preparation of mocked structures for unit tests under XUnit2 by configuring AutoFixture data generation to use a mocking library of your choice. Gracefully handles recursive structures by omitting recursions.

It provides the following mocking attributes:

  • AutoMockData
  • InlineAutoMockData
  • MemberAutoMockData

Supported mocking libraries

Mocking library Corresponding NuGet package
Moq AutoMoq Downloads
NSubstitute AutoNSubstitute Downloads
FakeItEasy AutoFakeItEasy Downloads

Attributes

AutoMockData

Provides auto-generated data specimens generated by AutoFixture with a mocking library as an extension to xUnit.net's Theory attribute.

Arguments

  • IgnoreVirtualMembers - disables generation of members marked as virtual; by default set to false

Example

[Theory]
[AutoMockData]
public void GivenCurrencyConverter_WhenConvertToPln_ThenMustReturnCorrectConvertedAmount(
    string testCurrencySymbol,
    [Frozen] ICurrencyExchangeProvider currencyProvider,
    CurrencyConverter currencyConverter)
{
    // Arrange
    Mock.Get(currencyProvider)
        .Setup(cp => cp.GetCurrencyExchangeRate(testCurrencySymbol))
        .Returns(100M);

    // Act
    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, 100M);

    // Assert
    Assert.Equal(10000M, result);
}

InlineAutoMockData

Provides a data source for a Theory, with the data coming from inline values combined with auto-generated data specimens generated by AutoFixture with a mocking library.

Arguments

  • IgnoreVirtualMembers - disables generation of members marked as virtual; by default set to false

Example

[Theory]
[InlineAutoMockData("USD", 3, 10, 30)]
[InlineAutoMockData("EUR", 4, 20, 80)]
public void GivenCurrencyConverter_WhenConvertToPln_ThenMustReturnCorrectConvertedAmount(
    string testCurrencySymbol,
    decimal exchangeRate,
    decimal currencyAmount,
    decimal expectedPlnAmount,
    [Frozen] ICurrencyExchangeProvider currencyProvider,
    CurrencyConverter currencyConverter)
{
    // Arrange
    Mock.Get(currencyProvider)
        .Setup(cp => cp.GetCurrencyExchangeRate(testCurrencySymbol))
        .Returns(exchangeRate);

    // Act
    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, currencyAmount);

    // Assert
    Assert.Equal(expectedPlnAmount, result);
}

MemberAutoMockData

Provides a data source for a Theory, with the data coming from one of the following sources:

  • A static property
  • A static field
  • A static method (with parameters)

combined with auto-generated data specimens generated by AutoFixture with a mocking library.

The member must return something compatible with Enumerable<object[]> with the test data.

Caution: The property is completely enumerated by .ToList() before any test is run. Hence it should return independent object sets.

Arguments

  • IgnoreVirtualMembers - disables generation of members marked as virtual; by default set to false
  • ShareFixture - indicates whether to share a fixture across all data items should be used or new one; by default set to true

Example

public class CurrencyConverterFixture
{
    public static IEnumerable<object[]> CurrencyConversionRatesWithResult()
    {
        return new List<object[]>
            {
                new object[] { "USD", 3M, 10M, 30M },
                new object[] { "EUR", 4M, 20M, 80M }
            };
    }
}
[Theory]
[MemberAutoMockData("CurrencyConversionRatesWithResult", MemberType = typeof(CurrencyConverterFixture))]
public void GivenCurrencyConverter_WhenConvertToPln_ThenMustReturnCorrectConvertedAmount(
    string testCurrencySymbol,
    decimal exchangeRate,
    decimal currencyAmount,
    decimal expectedPlnAmount,
    [Frozen] ICurrencyExchangeProvider currencyProvider,
    CurrencyConverter currencyConverter)
{
    // Arrange
    Mock.Get(currencyProvider)
        .Setup(cp => cp.GetCurrencyExchangeRate(testCurrencySymbol))
        .Returns(exchangeRate);

    // Act
    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, currencyAmount);

    // Assert
    Assert.Equal(expectedPlnAmount, result);
}

IgnoreVirtualMembers

An attribute that can be applied to parameters in an AutoDataAttribute-driven Theory to indicate that the parameter value should not have virtual properties populated when the IFixture creates an instance of that type.

This attribute allows to disable the generation of members marked as virtual on a decorated type wheres IgnoreVirtualMembers arguments of mocking attributes mentioned above disable such a generation for all types created by IFixture.

Caution: Order is important! Applying IgnoreVirtualMembers attribute to the subsequent paramater makes precedig parameters of the same type to have virtual properties populated and the particular parameter with the following ones of the same type to have virtual properties unpopulated.

Example

public class User
{
    public string Name { get; set; }
    public virtual Address Address { get; set; }
}
[AutoData]
[Theory]
public void IgnoreVirtualMembersUsage(
    User firstUser,
    [IgnoreVirtualMembers] User secondUser,
    User thirdUser)
{
    Assert.NotNull(firstUser.Name);
    Assert.NotNull(firstUser.Address);

    Assert.NotNull(secondUser.Name);
    Assert.Null(secondUser.Address);

    Assert.NotNull(thirdUser.Name);
    Assert.Null(thirdUser.Address);
}

Tips and tricks

Fixture injection

You can inject same instance of IFixture to a test method by adding mentioned interface as an argument of test method.

[Theory]
[AutoMockData]
public void FixtureInjection(IFixture fixture)
{
    Assert.NotNull(fixture);
}

IgnoreVirtualMembers issue

You should be aware that the CLR requires that interface methods be marked as virtual. Please look at the following example:

public interface IUser
{
    string Name { get; set; }
    User Substitute { get; set; }
}

public class User : IUser
{
    public string Name { get; set; }
    public virtual User Substitute { get; set; }
}

You can see than only Substitute property has been explicitly marked as virtual. In such situation the compiler will mark other properties as virtual and sealed. And finally AutoFixture will assign null value to those properties when option IgnoreVirtualMembers will be set to true.

[Theory]
[AutoMockData(IgnoreVirtualMembers = true)]
public void IssueWithClassThatImplementsInterface(User user)
{
    Assert.Null(user.Name);
    Assert.Null(user.Substitute);
}

License

FOSSA Status

About

Autofixture auto-mocking for XUnit2 using Moq.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 100.0%