65.9K
CodeProject is changing. Read more.
Home

FakeItEasy, AutoData and InlineAutoData

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (3 votes)

Dec 13, 2018

CPOL
viewsIcon

6109

FakeItEasy, AutoData and InlineAutoData in action

Introduction

Getting InlineAutoData to co-work with FakeItEasy is very useful. But how do you do it?

When writing unit tests, you will want to use InlineData to run your tests with multiple datasets. In many cases, you will also want to be able to use fakes, and control their response.

When working with xUnit, AutoData and FakeItEasy, you may find it a difficult setup. And you will be having a hard time to find a solution when "asking google".

It is however possible.

Background

Using InlineAutoData inhibits the use of FakeItEasy fakes, unless you customize InlineAutoData.

Using the Code

I want to combine InLineAutoData with FakeItEasy like this:

        [Theory]
        [InlineAutoFakeItEasyData(1, 2, 400, 1000, 0, 600, 400)]
        public void When_Credit_Not_Excceded__Then_Amount_Is_Transferd
        (
            int fromAccount,
            int toAccount,
            decimal amount,
            decimal saldo1,
            decimal saldo2,
            decimal expectedSaldo1,
            decimal expectedSaldo2,
            [Frozen] IKontoRepository kontoRepository,
            Transfer sut)
        {
            // Arrange
            A.CallTo(() => kontoRepository.GetSaldo(fromAccount)).Returns(saldo1);
            A.CallTo(() => kontoRepository.GetSaldo(toAccount)).Returns(saldo2);

            // Act
            (sut as ITransfer).Transfer(fromAccount, toAccount, amount);

            // Assert
            Assert.True(false);
        }

Being able to use both autodata and fakes as parameters.

After a lot of "google", I found a solution:

Add this code to your project:

    public class AutoFakeItEasyDataAttribute : AutoDataAttribute
    {
        public AutoFakeItEasyDataAttribute()
            : base(() => new Fixture().Customize(new AutoFakeItEasyCustomization()))
        {
        }
    }

    public class InlineAutoFakeItEasyDataAttribute : CompositeDataAttribute
    {
        public InlineAutoFakeItEasyDataAttribute(params object[] values) : 
                                               base(new InlineDataAttribute(values),
            new AutoFakeItEasyDataAttribute())
        {
        }
    }

Happy coding! :-)