9
votes

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!

1
Thanks for your answer. The problem is that in Christ's post he did not parse the HttpPostedFileBase as a parameter into the controller. However, in Phil's method the controller should take HttpPostedFileBase as parameter which is bounded with HttpFileCollectionValueProvider. So that is my problem with unit testing here...Seen

1 Answers

7
votes

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?