Take the 2-minute tour ×

I am trying to unittest a file upload but seem to be missing something.

The controller contains this fairly standard block in the httpPost handler:

foreach (string file in Request.Files) {
    var postedFile = Request.Files[file] as HttpPostedFileBase;
    if (postedFile.ContentLength == 0)
    var fileName = "~/Uploaded/" + Path.GetFileName(postedFile.FileName);

For the unittest I am using Moc:

var mock = new Mock<ControllerContext>();

mock.Setup(p => p.HttpContext.Request.Files.Count).Returns(0);

// also tried unsuccessfully:
// var collection = new Mock<HttpFileCollectionBase>();
// mock.Setup(p => p.HttpContext.Request.Files).Returns(collection.Object);
// mock.Setup(p => p.HttpContext.Request.Files.AllKeys).Returns(new string[] {});

var controller = CreateReportsController();
controller.ControllerContext = mock.Object;

My hope was that the mocked context would simulate a valid request without any file upload. Instead it will fail at the foreach statement with a nullreference exception. I can see why, since I haven't actually set Request.Files but I am not sure how to do better.

So, how do I configure the moc context correctly?

Thanks, Duffy

share|improve this question
add comment

1 Answer

You need to create an automatic recursive mock:

var mock = new Mock<ControllerContext> { DefaultValue = DefaultValue.Mock };

More Moq solutions are available here: http://code.google.com/p/moq/wiki/QuickStart

share|improve this answer
add comment

Your Answer


