Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture: Supply a Func as a constructor argument

Tags:

c#

autofixture

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.

like image 245
Mdb Avatar asked Dec 26 '22 03:12

Mdb


1 Answers

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.

like image 69
Nikos Baxevanis Avatar answered Jan 12 '23 17:01

Nikos Baxevanis