使用 Autofac 对委托工厂进行单元测试

Dav*_*Dev 4 c# unit-testing autofac

我正在努力通过一些众多的 DI 框架来证明依赖注入的使用。我正在尝试对当前使用 Autofac 作为 DI 容器的一些类进行单元测试。

假设我有这门课...

public class SaveUserCommand : DBCommandBase<UserImpl>
{
    public delegate SaveUserCommand Factory(UserImpl impl);

    private UserImpl impl;
    private IAuditableHelper helper;

    public SaveUserCommand(UserImpl impl, IAuditableHelper helper)
    {
        this.impl = impl;
        this.helper = helper;
    }

    public override UserImpl Execute(object dataTrans)
    {
        return this.impl;
    }
}
Run Code Online (Sandbox Code Playgroud)

^命令结构化业务层顺便说一句。

我有另一个命令以这种方式依赖于上面的命令......

public class SaveSpecialUserCommand : DBCommandBase<UserImpl>
{
    public delegate SaveSpecialUserCommand Factory(UserImpl user);

    private UserImpl user;
    SaveUserCommand.Factory saveUserCommand;

    public SaveSpecialUserCommand(UserImpl user, SaveUserCommand.Factory saveUserCommand)
    {
        this.user = user;
        this.saveUserCommand = saveUserCommand;
    }

    public override UserImpl Execute(object dataTrans)
    {
        this.user.IsSpecial = true;
        this.saveUserCommand(this.user).Execute(dataTrans);
        return this.user;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 Autofac,它可以解决SaveSpecialUserCommand.

我不确定的是如何对委托进行单元测试或注入模拟SaveUserCommand.Factory

提示会很好。我仍然想弄清楚这一点,但有一个大方向就很棒了。

编辑

只需添加一个简单的测试用例,显示我不想在单元测试中使用 Autofac 来创建命令。

    [Test]
    public void SomeSimpleTestTest()
    {
        var user = new UserImpl();

        var command = new SaveSpecialUserCommand(user, /*This is what I need to mock. SaveUserCommand.Factory*/null);
        var retVal = command.Execute(this._mockTransaction);

        Assert.IsNotNull(retVal);
        Assert.IsTrue(retVal.IsSpecial);
    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*old 5

如果您SaveSpecialUserCommand通过容器进行解析,则无法模拟工厂委托,因为这是 Autofac 为您自动生成的部分。那么问题是,为什么需要伪造实际的委托呢?

更新:最初存在一些误解。要“伪造”委托,您可以简单地使用 lambda,如下所示:

var user = new UserImpl();
var cmd = new SaveUserCommand(...);

var command = new SaveSpecialUserCommand(user, u => cmd);
Run Code Online (Sandbox Code Playgroud)