Reputation: 2414
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);
}
Upvotes: 4
Views: 1711
Reputation: 33920
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);
Upvotes: 5