Reputation: 8556
I am quite new to unit testing and am doing some experiments with xUnit and AutoFixture.
This is the constructor of the class I want to test:
public PokerClientIniGenerateCommand(
Func<TextWriter> writerCreator,
FranchiseInfo franchise)
{
// some code here
}
I am doing this:
public abstract class behaves_like_poker_client_ini_generate_command : Specification
{
protected PokerClientIniGenerateCommand commandFixture;
protected behaves_like_poker_client_ini_generate_command()
{
var fixture = new Fixture();
commandFixture = fixture.Create<PokerClientIniGenerateCommand>();
}
}
I am not sure how can I set the constructor parameters ( mainly the first parameter - the func part).
In my business logic I am instantiating this class like this:
new PokerClientIniGenerateCommand(
() => new StreamWriter(PokerClientIniWriter),
franchise));
so in my test I should call the func like this:
() => new StringWriter(PokerClientIniWriter)
But how can I set this via the AutoFixture. Any help will example will be greatly appreciated.
Upvotes: 4
Views: 1233
Reputation: 11211
From version 2.2 and above, AutoFixture handles Func
and Action
delegates automatically.
In your example, you only have to inject a StringWriter
type as a TextWriter
type, as shown below:
fixture.Inject<TextWriter>(new StringWriter());
You can read more about the Inject
method here.
Upvotes: 7
Reputation: 59983
As @NikosBaxevanis correctly points out in his answer, AutoFixture is able to create anonymous instances of any delegate type. These anonymous delegates take the form of dynamically generated methods.
The generation strategy, as it's currently implemented, follows these rules:
void
, the created method will be a
no-op.T
, the created method will return an anonymous instance of T
.Given these rules, in the case of Func<TextWriter>
it would be enough to just customize the creation of anonymous TextWriter
objects with:
fixture.Register<TextWriter>(() => new StringWriter());
Upvotes: 5
Reputation: 8556
I managed to do this:
fixture.Register<Func<TextWriter>>(() => () => new StringWriter());
Upvotes: -1