Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing a Delegate Factory with Autofac

I'm working on proving out using Dependency Injection with some numerous DI frameworks. I'm attempting to try to unit test some classes currently using Autofac as the DI container.

Let's say I have this class...

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;
    }
}

^Command structured business layer btw.

I have another command that relies on the above command in this way...

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;
    }
}

Using Autofac, it resolves all dependencies in the SaveSpecialUserCommand.

What I am unsure of, is how I can unit test or inject a mock into the SaveUserCommand.Factory delegate.

Hints would be good. I still want to figure this out, but a general direction would be awesome.

EDIT

Just adding a simple test case showing I do not want to use Autofac in my unit tests to create my commands.

    [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);
    }
like image 570
DavidAndroidDev Avatar asked Nov 16 '25 19:11

DavidAndroidDev


1 Answers

If you resolve SaveSpecialUserCommand through the container, you can't mock the factory delegate since this is a piece that Autofac autogenerates for you. The question is then, why do you need to fake the actual delegate?

Update: bit of misunderstanding initially there. To "fake" a delegate you can simply use a lambda, like this:

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

var command = new SaveSpecialUserCommand(user, u => cmd);
like image 161
Peter Lillevold Avatar answered Nov 18 '25 09:11

Peter Lillevold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!