【问题标题】:Testing a asp.net project IHttpHandler , issue with Request.Files测试一个 asp.net 项目 IHttpHandler , Request.Files 问题
【发布时间】:2014-08-21 21:26:11
【问题描述】:

出于测试目的,我需要传递一个 HttpFileCollection 实例来进行模拟上传。问题是:我不能模拟这个,因为我需要再次下载文档以仔细检查它作为集成测试。

最大的问题是HttpFileCollection的构造函数被保护了。

谁能帮帮我?

我正在使用类似于这个的自定义 testHandler:

http://blogs.cozi.com/techold/2008/05/a-way-to-unit-t.html

被测代码如下:

 public class DocumentUploadHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {

        var jArray = new JArray();
        bool errorOccured = false;

        var files = context.Request.Files;

        var queryParams = context.Request.QueryString.AllKeys.ToDictionary(k => k.ToLowerInvariant(),
            k => context.Request.QueryString[k]);


        using (var session = Connection.SessionFactory.OpenSession())
        using (var tx = session.BeginTransaction())
        {
            try
            {
                int qsSessionId = 0;

                if (!queryParams.ContainsKey("sessionid"))
                {
                    throw new ArgumentException("Parameter missing.", "sessionid");
                };


                if (!int.TryParse(queryParams["sessionid"], out qsSessionId))
                {
                    throw new ArgumentException("Parameter malformed.", "sessionid");  
                };


                var activity = session.Query<Activity>().Fetch(x=>x.Contact).FirstOrDefault(x => x.Session == qsSessionId);

                if (activity == null)
                {
                    throw new Exception("Session not found.");
                }

                string qsFilename = "";

                if (queryParams.ContainsKey("filename") && !string.IsNullOrWhiteSpace(queryParams["filename"]))
                    qsFilename = queryParams["filename"];

                for (int i = 0; i < files.Count; i++)
                {
                    if (files[i].ContentLength > 0)
                    {
                        var now = DateTime.Now;

                        var filename = "";

                        if (string.IsNullOrWhiteSpace(qsFilename))
                        {

                            filename = string.Format("{0}_{1}_{2}{3}",
                                Path.GetFileNameWithoutExtension(files[i].FileName), 
                                activity.Contact.Login,
                                DateUtils.IsoDateTimeToString(now), 
                                Path.GetExtension(files[i].FileName));
                        }
                        else
                        {
                            filename = string.Format("{0}_{1}_{2}{3}", 
                                qsFilename,
                                activity.Contact.Login,
                                DateUtils.IsoDateTimeToString(now),
                                Path.GetExtension(files[i].FileName));

                        }

                        var document = new Document
                        {
                            Code = filename,
                            Filename = filename,
                            FileExtension = Path.GetExtension(files[i].FileName),
                            Client = session.Load<Client>(801),
                            DocumentType = session.Load<DocumentType>(430),
                            Imported = now,
                            Modified = now
                        };

                        var fileByteArray = new byte[files[i].ContentLength];

                        files[i].InputStream.Read(fileByteArray, 0, files[i].ContentLength);
                        document.FileData = ZlibStream.CompressBuffer(fileByteArray);
                        session.Save(document);
                        jArray.Add(document.Id);
                    }
                }
                tx.Commit();
            }
            catch (Exception exception)
            {
                tx.Rollback();
                context.Response.Clear();
                context.Response.StatusCode = 200;
                context.Response.ContentType = "application/json; charset=utf-8";
                context.Response.Output.Write(JsonConvert.SerializeObject(exception, Formatting.Indented));
                context.Response.Output.Close();

                context.Response.Flush();

                errorOccured = true;
            }
        }

        if (errorOccured == false)
        {
            context.Response.Clear();
            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.Output.Write(jArray.ToString());
            context.Response.Output.Close();

            context.Response.Flush();

        }


    }

问候

编辑:澄清这一点:如果不向 .asax 端发送真正的 Webrequest,我将如何测试它?我不希望服务器作为我的测试的要求运行

【问题讨论】:

  • 指出哪里调用了构造函数?
  • 问题是没有调用构造函数但使用了属性: var files = context.Request.Files;为了测试它,我必须构建一个 HttpFileCollection 对象并设置 context.request.files。首先没有设置器,其次没有公共构造函数可以做到这一点。

标签: c# asp.net testing upload mocking


【解决方案1】:

在最坏的情况下,您可以通过反射访问受保护的构造函数来创建实例。

MSDN

Similar post on stackoverflow

【讨论】:

  • 我已经尝试了很多方法。我现在真的会试试这个。
  • 问题在于:Context.Request.Files 没有可使用的设置器,所以即使我可以创建一个对象,我也无法将它传递给上下文
  • 您还可以检索私有字段或设置器(如果存在)。
  • 但我无法设置,这才是真正的问题
  • 我说的是字段,不是属性。当然你可以设置一个属性。
猜你喜欢
  • 2011-06-12
  • 1970-01-01
  • 2011-02-23
  • 2010-10-05
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
相关资源
最近更新 更多