views:

26

answers:

1

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)
        continue;
    var fileName = "~/Uploaded/" + Path.GetFileName(postedFile.FileName);
    postedFile.SaveAs(Server.MapPath(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

A: 

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

marcind