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
Ways to write unit test code for File upload on Controllers: For file upload related testing we need to Mock HTTPContext, HTTPContext. Server and HttpPostedFileBase. These classes handle the file uploading and saving.
Mocking is a process that allows you to create a mock object that can be used to simulate the behavior of a real object. You can use the mock object to verify that the real object was called with the expected parameters, and to verify that the real object was not called with unexpected parameters.
Mocking provides the ability to simulate an object. For example, you can test a call to a database without having to actually talk to it. The Moq framework is an open source unit testing framework that works very well with .
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With