Search code examples
unit-testingmodel-view-controllermockingrhino-mocks

MVC Rhino Mocks for Request.Files


I'm trying to get my controller in a unit test to return a mock file when Request.Files[0] is called

From other posts on this site I've put together:

[TestMethod]
        public void CreateFileInDatabase()
        {
            var repository = new MocRepository();
            var controller = GetController(repository);

            HttpContextBase mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
            HttpRequestBase mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
            mockHttpContext.Stub(x => x.Request).Return(mockRequest);

            mockRequest.Stub(x => x.HttpMethod).Return("GET");

            var filesMock = MockRepository.GenerateMock<HttpFileCollectionBase>();
            var fileMock = MockRepository.GenerateMock<HttpPostedFileBase>();
            filesMock.Stub(x => x.Count).Return(1);
            mockRequest.Stub(x => x.Files).Return(filesMock);
            var t = mockHttpContext.Request;

            var automobile = new Automobile{ automobileNumber = "1234" };
            controller.ControllerContext = new ControllerContext(mockHttpContext, new RouteData(), controller);
            controller.Create(automobile);
        }

When I'm in the controller during a test and call Request.Files I get the filesMock great.

However I want to be able to call Request.Files[0] and get a mock File which I can pass as a parameter to a method.

I haven't done much mocking before so any help would be appreciated!


Solution

  • Your filesMock object is a mock, therefore it have no idea how to resolve Files[0]. You need to tell it what to return, if someone asks for the first file:

    filesMock.Stub(x => x[0]).Return(fileMock);
    

    Add the above line after the creation of the fileMock object and the code works :)