views:

154

answers:

2

I want to test a controller method in MVC unit test. For my controller method to test, I require a Request.Files[] collection with length one. I want to mock Request.Files[] as I have used a file upload control on my view rendered by controller method. Can anyone please suggest how can I mock request.file collection in my unit test.

thanks, kapil

+1  A: 

You didn't mention what mocking framework you are using but here's how you would do it with Rhino Mocks:

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(Request.Files.Count);
    }
}

Unit test:

[TestMethod]
public void SomeTest()
{
    // arrange
    var controller = new HomeController();
    var context = MockRepository.GenerateStub<HttpContextBase>();
    var request = MockRepository.GenerateStub<HttpRequestBase>();
    var files = MockRepository.GenerateStub<HttpFileCollectionBase>();
    context.Stub(x => x.Request).Return(request);
    files.Stub(x => x.Count).Return(5);
    request.Stub(x => x.Files).Return(files);
    controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);


    // act
    var actual = controller.Index();

    // assert
    Assert.IsInstanceOfType(actual, typeof(ViewResult));
    var viewResult = actual as ViewResult;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(int));
    Assert.AreEqual(5, viewResult.ViewData.Model);
}

Remark: Using MVCContrib.TestHelper this test could be greatly simplified especially the context mocking part and the asserts as well:

[TestMethod]
public void SomeTest()
{
    // arrange
    var sut = new HomeController();
    InitializeController(sut);
    Files["test.txt"] = MockRepository.GenerateStub<HttpPostedFileBase>();

    // act
    var actual = sut.Index();

    // assert
    actual
        .AssertViewRendered()
        .WithViewData<int>()
        .ShouldBe(1);
}
Darin Dimitrov
Thanks Darin. I am using open source mocking framework "Moq".
kapil