Click here to Skip to main content
15,902,832 members
Articles / Programming Languages / C#
Tip/Trick

FakeItEasy, AutoData and InlineAutoData

Rate me:
Please Sign up or sign in to vote.
4.20/5 (3 votes)
13 Dec 2018CPOL 5.8K   2  
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:

C#
[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:

C#
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! :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer UCL Erhvervsakademi og Professionshøjskole UCL Erhvervsakademi og Professionshøjskole
Denmark Denmark
ORCID: 0000-0002-8974-2718

Comments and Discussions

 
-- There are no messages in this forum --