I am wanting to write up a unit test that checks that a specific Unity IoC object was instantiated.
For example, here is the class I am testing.
using Microsoft.Practices.Unity;
using System.Threading;
namespace Client.Engine
{
public sealed class Uploader : IUploader
{
private readonly IUnityContainer _container;
public Uploader(IUnityContainer container)
{
_container = container;
}
public void PerformUpload(CancellationToken token, int batchSize)
{
token.ThrowIfCancellationRequested();
_container.Resolve<IUploadModule>("Clients").Upload(token, batchSize);
token.ThrowIfCancellationRequested();
_container.Resolve<IUploadModule>("Patients").Upload(token, batchSize);
}
}
}
And here is the unit tests I set up
[TestClass()]
public class UploadClientsTests : UploadModuleTestsBase
{
[TestMethod()]
public override void UploaderRegrestrationTest()
{
PerformRegistrationTest("Clients");
}
}
[TestClass()]
public class UploadPatientsTests : UploadModuleTestsBase
{
[TestMethod()]
public override void UploaderRegrestrationTest()
{
PerformUpladerRegistrationTest("Patients");
}
}
public class UploadPatientsTests : UploadModuleTestsBase
{
protected static void PerformUpladerRegistrationTest(string moduleName)
{
var container = new UnityContainer();
var mocker = new AutoMoqer(container);
var random = new Random();
int batchSize = random.Next(int.MaxValue);
var token = new CancellationToken();
var uploadModuleMock = new Mock<IUploadModule>();
uploadModuleMock.Setup(module => module.Upload(token, batchSize)).Verifiable();
container.RegisterInstance(typeof(IUploadModule), moduleName, uploadModuleMock.Object, new ContainerControlledLifetimeManager());
container.RegisterInstance(typeof(IUploadModule), Mock.Of<IUploadModule>());
var uploader = mocker.Resolve<Uploader>();
uploader.PerformUpload(token, batchSize);
uploadModuleMock.Verify();
}
}
The problem I run in to is Unity 2.0 does not fall back to the default instance if a named type is not available. So if I comment out the _container.Resolve<IUploadModule>("Patients")
line the clients test works perfectly, and if I comment out _container.Resolve<IUploadModule>("Clients")
the patients test works perfectly, I just don't know how to make it so both can co-exist.
EDIT: In normal operation I am restringing the two objects like this.
public static Bootstrap(IUnityContainer container)
{
container.RegisterType<IUploadModule, UploadClients>("Clients", new HierarchicalLifetimeManager());
container.RegisterType<IUploadModule, UploadPatients>("Patients", new HierarchicalLifetimeManager());
}