I have a Mock challenge – I’m using MVC 3 with the nunit framework and trying to mock a controller has an HttpPostedFileBase as a parameter. The controller signature looks like this:
public ActionResult UploadAttachment(AttachmentViewModel clientAttachment, HttpPostedFileBase file, string clientName)
I set up a Mock reference for my “file” parameter, but it complains that it will not take a Mock Object. I’m guessing that I need to set up a ControllerContext for this scenario, but I haven’t had any luck with that, either. For the first test I simply need the HttpPostedFileBase to return a null file (in the case that a blank file reference gets in). I have also read Scott Hanselman’s excellent article on this subject (computer Zen). It seems like the key sentence in the MVC section for my concern is “you’ll get a dynamically generated derived Mock of an HttpRequestBase while running outside a Webserver (like inside a test) when you’ve made your own ControllerContext.” That seems to be where I’m running into walls.
I know I need these elements:
controller.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), controller);
mockContext.SetupGet(c => c.Request).Returns(mockRequest.Object);
mockRequest.Setup(c => c.HttpMethod).Returns([not sure what to evoke here]);
I’m in the state of being stuck. Thank you for any advice or nudges in the right direction.
Assuming you use a real view model (which is used by your controller action, instead of using a gazillion of parameters):
and a controller with an action that you are trying to unit test:
you now have 2 cases to cover:
Let’s get rolling:
and the second case of course:
Hope this will put you on the right track. Sorry it uses MSTest instead of NUnit but the port should be more than trivial (shouldn’t take you more than 30man-seconds of work). Replace
[TestMethod]with[Test]and you should not be far from the target. And yeah, I bet 2¢ that thisAssert.IsInstanceOfTypehas an equivalent in NUnit.