9

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!

2
  • Try this: ASP.NET MVC: Unit Test File Upload with Moq Commented Apr 1, 2011 at 15:24
  • 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... Commented Apr 1, 2011 at 15:47

1 Answer 1

7

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I figure out the problem is that I didn't set up the right repository for Moq. I looked at the document for Moq and get the right codes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.