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 dataset
s. 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)
{
A.CallTo(() => kontoRepository.GetSaldo(fromAccount)).Returns(saldo1);
A.CallTo(() => kontoRepository.GetSaldo(toAccount)).Returns(saldo2);
(sut as ITransfer).Transfer(fromAccount, toAccount, amount);
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! :-)