CodeGuru
CodeGuru

Reputation: 2803

Mock httpcontext.current.request.files

I am implementing nUnit Test case for one of my method called, UploadFile(), some thing like below

 public void UploadFile(string siteId, string sitePageId)
 {
    int fileCount = HttpContext.Current.Request.Files.Count;

    //Rest of code
 }

so basically i am reading file using HttpContext.Current.Request.Files. From UI it is working fine but when i am implementing nUnit test case for it, i am not able to mock HttpContext.Current.Request.Files. I googled about some of mocking tools but there also i didn't get anything related to mocking of HttpContext.Current.Request.Files. Please help me how to mock it or write test case for my method.

Upvotes: 0

Views: 2954

Answers (1)

Kenneth
Kenneth

Reputation: 28737

You could use dependency injection and then inject an instance of HttpContextBase into the class. Supposing you're using MVC:

public class MyController : Controller
{

    HttpContextBase _context;        

    public MyController(HttpContextBase context)
    {
        _context = context
    }

    public void UploadFile(string siteId, string sitePageId)
    {
        int fileCount = _context.Request.Files.Count;

        //Rest of code
    }
}

Now you can instantiate the controller with a mock of HttpContextBase. This is how you would do it with Moq:

[Test]
public void File_upload_test()
{
    var contextmock = new Mock<HttpContextBase>();
    // Set up the mock here
    var mycontroller = new MyController(contextmock.Object);
    // test here
}

Upvotes: 2

Related Questions