I’m trying to get Deleporter to do some cross process integration testing. The tests are being run using WatiN against our ASP.NET MVC3 application. We use Autofac for dependency injection.
I’ve looked at Steve Sanderson’s blog about setting it up to return a mock repository using NInject.
// Inject a mock IDateProvider, setting the clock back to 1975
var dateToSimulate = new DateTime(1975, 1, 1);
Deleporter.Run(() => {
var mockDateProvider = new Mock<idateProvider>();
mockDateProvider.Setup(x => x.CurrentDate).Returns(dateToSimulate);
NinjectControllerFactoryUtils.TemporarilyReplaceBinding(mockDateProvider.Object);
});
Is there an Autofac equivalent of TemporarilyReplaceBinding?
I’ve tried the following below but get an error of “The request lifetime scope cannot be created because the HttpContext is not available.”
The table is being passed by SpecFlow.
var tableSerialized = new SerializableTable(table);
Deleporter.Run(() =>
{
var mockRepository = new Mock<IRepository<SmsMessageReceived>>();
mockRepository.Setup(x => x.Table)
.Returns((from row in tableSerialized.Rows
select new SmsMessageReceived
{
DateCreated = DateTime.Now,
Id = Int32.Parse(row[ColumnId]),
MessageBody = row[ColumnMessageBody]
}).AsQueryable() as IQueryable<SmsMessageReceived>);
var builder = new ContainerBuilder();
builder.RegisterInstance(mockRepository.Object);
var container = builder.Build();
builder.Update(container);
});
This was an error on my part. In the code above I missed out how I was obtaining the container to be updated. I was doing this through a call to
DependencyResolver.Current.GetService()
this was what was throwing the error about HttpContext not available.
I stripped this out and then in my Global.asax.cs I added a static instance to hold the built up IContainer. So changing the code that Deleporter runs to
MvcApplication is the class in Global.asax.cs.
Then added a reference to Moq to my web project and now it works perfectly.
I do wonder whether there’s a better way to get the container than a static, but this does work.