Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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:

  1. If the delegate's signature is void, the created method will be a no-op.
  2. If the delegate's signature has a return value 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());

I managed to do this:

fixture.Register<Func<TextWriter>>(() => () => new StringWriter());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top