C# 如何构建HttpPostedFileBase?
我必须为此方法编写一个单元测试,但我无法构造HttpPostedFileBase。。。当我在浏览器中运行这个方法时,它运行得很好,但是我确实需要一个自动的单元测试。所以我的问题是:如何构造HttpPosterFileBase以便将文件传递给HttpPostedFileBase 谢谢C# 如何构建HttpPostedFileBase?,c#,asp.net-mvc,asp.net-mvc-2,file-upload,C#,Asp.net Mvc,Asp.net Mvc 2,File Upload,我必须为此方法编写一个单元测试,但我无法构造HttpPostedFileBase。。。当我在浏览器中运行这个方法时,它运行得很好,但是我确实需要一个自动的单元测试。所以我的问题是:如何构造HttpPosterFileBase以便将文件传递给HttpPostedFileBase 谢谢 public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files) { foreach (var f
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
// ...
}
}
public ActionResult上传文件(IEnumerable文件)
{
foreach(文件中的var文件)
{
// ...
}
}
这样做怎么样:
public class MockHttpPostedFileBase : HttpPostedFileBase
{
public MockHttpPostedFileBase()
{
}
}
然后您可以创建一个新的:
MockHttpPostedFileBase mockFile = new MockHttpPostedFileBase();
在我的例子中,我通过asp.net MVC web界面、RPC webservice和unittest使用核心注册核心。在这种情况下,为HttpPostedFileBase定义自定义包装器非常有用:
public class HttpPostedFileStreamWrapper : HttpPostedFileBase
{
string _contentType;
string _filename;
Stream _inputStream;
public HttpPostedFileStreamWrapper(Stream inputStream, string contentType = null, string filename = null)
{
_inputStream = inputStream;
_contentType = contentType;
_filename = filename;
}
public override int ContentLength { get { return (int)_inputStream.Length; } }
public override string ContentType { get { return _contentType; } }
/// <summary>
/// Summary:
/// Gets the fully qualified name of the file on the client.
/// Returns:
/// The name of the file on the client, which includes the directory path.
/// </summary>
public override string FileName { get { return _filename; } }
public override Stream InputStream { get { return _inputStream; } }
public override void SaveAs(string filename)
{
using (var stream = File.OpenWrite(filename))
{
InputStream.CopyTo(stream);
}
}
公共类HttpPostedFileStreamWrapper:HttpPostedFileBase
{
字符串_contentType;
字符串_文件名;
流_输入流;
公共HttpPostedFileStreamRapper(流输入流,字符串内容类型=null,字符串文件名=null)
{
_inputStream=inputStream;
_contentType=contentType;
_filename=文件名;
}
公共重写int ContentLength{get{return(int)_inputStream.Length;}
公共重写字符串ContentType{get{return}
///
///总结:
///获取客户端上文件的完全限定名。
///返回:
///客户端上的文件名,包括目录路径。
///
公共重写字符串文件名{get{return_FileName;}}
公共重写流InputStream{get{return}InputStream;}
公共覆盖无效保存为(字符串文件名)
{
使用(var stream=File.OpenWrite(文件名))
{
InputStream.CopyTo(流);
}
}