首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何构建HttpPostedFileBase?

如何构建HttpPostedFileBase?
EN

Stack Overflow用户
提问于 2010-08-07 06:35:03
回答 2查看 5.4K关注 0票数 5

我必须为这个方法写一个单元测试,但是我不能构造HttpPostedFileBase...当我在浏览器中运行该方法时,它工作得很好,但我真的需要一个自动单元测试。所以我的问题是:为了将文件传递给HttpPostedFileBase,我如何构造HttpPosterFileBase。

谢谢。

代码语言:javascript
复制
    public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
           // ...
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-08-09 20:45:34

这样做怎么样:

代码语言:javascript
复制
public class MockHttpPostedFileBase : HttpPostedFileBase
{
    public MockHttpPostedFileBase()
    {

    }
}

然后,您可以创建一个新的:

代码语言:javascript
复制
MockHttpPostedFileBase mockFile = new MockHttpPostedFileBase();
票数 7
EN

Stack Overflow用户

发布于 2014-03-02 03:08:05

在我的例子中,我通过asp.net MVC web接口和RPC web服务以及通过unittest使用核心注册核心。在这种情况下,为HttpPostedFileBase定义自定义包装器非常有用:

代码语言:javascript
复制
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);
        }
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3428276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档