简体   繁体   English

AutoFixture:提供一个Func作为构造函数参数

[英]AutoFixture: Supply a Func as a constructor argument

I am quite new to unit testing and am doing some experiments with xUnit and AutoFixture. 我对单元测试很新,并且正在使用xUnit和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). 我不知道如何设置构造函数参数(主要是第一个参数--func部分)。

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: 所以在我的测试中我应该像这样调用func:

() => new StringWriter(PokerClientIniWriter)

But how can I set this via the AutoFixture. 但是如何通过AutoFixture设置它。 Any help will example will be greatly appreciated. 任何帮助将举例如将非常感谢。

From version 2.2 and above, AutoFixture handles Func and Action delegates automatically. 从2.2版及更高版本开始 ,AutoFixture会自动处理FuncAction代理。

In your example, you only have to inject a StringWriter type as a TextWriter type, as shown below: 在您的示例中,您只需要将StringWriter类型作为TextWriter类型注入,如下所示:

fixture.Inject<TextWriter>(new StringWriter());

You can read more about the Inject method here . 您可以在此处阅读有关Inject方法的更多信息。

As @NikosBaxevanis correctly points out in his answer, AutoFixture is able to create anonymous instances of any delegate type . 正如@NikosBaxevanis在他的回答中正确指出的那样,AutoFixture能够创建任何委托类型的匿名实例 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 . 如果委托的签名void ,则创建的方法将为no-op
  2. If the delegate's signature has a return value T , the created method will return an anonymous instance of T . 如果委托的签名具有返回值T ,则创建的方法将返回T的匿名实例。

Given these rules, in the case of Func<TextWriter> it would be enough to just customize the creation of anonymous TextWriter objects with: 根据这些规则,在Func<TextWriter>的情况下,仅使用以下内容自定义匿名TextWriter对象的创建就足够了:

fixture.Register<TextWriter>(() => new StringWriter());

我成功地做到了这一点:

fixture.Register<Func<TextWriter>>(() => () => new StringWriter());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM