Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Asp.net MVC fileUpload

Hello I am new in TDD development.
I came across this post for Using asp.net mvc to upload file
Phil Haack states that a class could be used for file upload control, in which he use the default HttpFileCollectionValueProvider:

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }

  return RedirectToAction("Index");
}

the value is bounded in a form as

<form action="" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
  <input type="submit" />
</form>

Note that the HttpPostedFileBase is parsed as a parameter into the controller with the name "file" in the html form and as parsing parameter in Index controller.

I have two questions:
1. How can I verify the file.SaveAs method?
2. I am not quite sure how to unit test with this. In the test controller file I should have a fake HttpPostedFileBase but it is sealed. Does anyone have some strategies to deal with this?

Thank you very much!

like image 710
Seen Avatar asked Apr 01 '11 15:04

Seen


1 Answers

My apologies if this isn't what you are asking but I would simply mock the HttpPostedFileBase in your test:

var file = MockRepository.GenerateStub<HttpPostedFileBase>();

and then set any expectations:

file.Expect(f => f.ContentLength).Return(1);
file.Expect(f => f.FileName).Return("myFileName");

then pass this to your controller method:

controller.Index(file);

So that you can mock the behaviour of your file. I'm not sure about the .SaveAs - have you overridden this method?

like image 166
JayneT Avatar answered Sep 18 '22 13:09

JayneT