Reputation: 18660
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!
Upvotes: 0
Views: 676
Reputation: 115006
The easiest way is to add an abstraction over the Request.Files[0]
via an interface and object that actually calls out to Request.Files[0]
Note: I'm not actually sure what the datatype is for Request.Files[0]
, just using IFile
as an example.
public interface IFileRetriever
{
IFile GetFile();
}
public class FileRetriever
{
public IFile GetFile()
{
return Request.Files[0];
}
}
Obviously suit the interface and real implementation to your use case, it will probably not be what is above...
In your class that currently calls out to Request.Files[0]
just take in the IFileRetriever as a dependency, which is straightforward to mock out in Rhino Mocks (or any mocking/faking framework)
Upvotes: 0
Reputation: 5259
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 :)
Upvotes: 1