Mock httpcontext.current.request.files

南楼画角 提交于 2019-12-11 23:14:37

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/21183816/mock-httpcontext-current-request-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!