How to unit-test a method that receives a FormCollection to upload a file?
Asked Answered
N

2

6

I want to Unit-test a method like the following:

public ActionResult StoreFile(FormCollection form, string _paginaAtual)
{
     Session["MySession"] = 1
     if (Request.Files["uploadedFiles"] != null)
         {
             //do something about the file
         }
     return View()
}

It's inside my "SomeController.cs" controller class and it is called when the user submits a file in a simple input type="file" HTML input.

P.S.: Purists beware: I KNOW this is not a "pure" unit testing, I just want to call the method in a test environment and check if it makes de desirable changes in the system.

Thank you all for any light in the subject, Lynx.

Nave answered 24/2, 2010 at 15:44 Comment(0)
S
5

Luckily the ASP.Net team thought about this before they started on MVC and created the System.Web.Abstractions namespace. It is a series of base classes that mirror the static classes that are impossible to test traditionally like the HttpWebRequest class.

What you want to do is rely on one of those base classes and do a little bit of dependency injection in order to effectively mock your session.

HttpSessionStateBase _session;
public HttpSessionStateBase Session
{
    get{
        return _session ?? (_session = new HttpSessionStateWrapper(HttpContext.Current.Session));
    }
    set{
        _session = value;
    }
}

As for the FormCollection, you don't have to mock it, as you should be able to create one apart from an HttpContext. There is a good example of that on Marcus Hammarberg's blog.

Sherrer answered 24/2, 2010 at 15:56 Comment(1)
Nice, I mock my session! But How do I mock the "FormCollection" ?Nave
M
0

What you're describing sounds more like integration testing. As for your FormCollection, if you wanted to isolate it, you could use an isolation framework like RhinoMocks, or "hand roll" your own mock for it.

Mccain answered 24/2, 2010 at 15:48 Comment(1)
Too bad I couldn't mock the FormCollection = (Nave

© 2022 - 2024 — McMap. All rights reserved.