3

For testing purposes I need to pass over an instance of HttpFileCollection to do a simulated upload. The thing is: I can't mock this because I need to download the document again to double check this as an integration test.

The biggest problem is that the constructor of HttpFileCollection is protected.

Cann anybody help me with that?

I am using a custom testHandler similar to this one:

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

The code under test is the following:

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

        }


    }

Greetings

Edit: To clarify this: How would I test this without sending an real Webrequest to the .asax side? I don't want the server to run as a requirement for my tests

  • point out where constructor is called? – Just code Jul 01 '14 at 13:20
  • The thing is the constructor isn't called but the property is used: var files = context.Request.Files; and in order to test it I would have to build a HttpFileCollection object and set the context.request.files. First of all there is no setter for that and second of all there is no public constructor to do this. – DisconnectYourNeighbours Jul 01 '14 at 13:21

1 Answers1

1

Worst case you can create an instance by reflection accessing a protected constructor, then.

MSDN

Similar post on stackoverflow

Community
  • 1
  • 1
jjaskulowski
  • 2,524
  • 3
  • 26
  • 36