如何单元测试Asp.net MVC文件上传 [英] How to unit test Asp.net MVC fileUpload

查看:214
本文介绍了如何单元测试Asp.net MVC文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在TDD发展的新。结果
我碰到这个职位来抓使用asp.net mvc的上传文件结果
菲尔哈克指出,一类可用于文件上传的控制,他在其中使用默认HttpFileCollectionValueProvider:

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");
}

该值的形式为界

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

请注意,该HttpPostedFileBase被解析为一个参数与HTML表单名为文件的控制器,并在控制器指数解析参数。

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.

我有两个问题:结果
1.如何验证file.SaveAs方法?结果
2.我不太清楚如何进行单元测试与此有关。在测试控制器文件,我应该有一个假的HttpPostedFileBase,但它是密封的。有没有人有一些策略来面对呢?

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?

非常感谢你!

推荐答案

我的道歉,如果这不是你问,但我只想嘲笑HttpPostedFileBase在您的测试:

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);

所以,你可以嘲笑你的文件的行为。我不知道对.SaveAs - 你重写这个方法

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

这篇关于如何单元测试Asp.net MVC文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆