模拟httpcontext.current.request.files [英] Mock httpcontext.current.request.files

查看:190
本文介绍了模拟httpcontext.current.request.files的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的一种方法 UploadFile()实现nUnit测试用例,如下所示

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
 }

所以基本上我正在使用 HttpContext.Current.Request.Files 读取文件. 从UI可以正常工作,但是当我为其实现nUnit测试用例时,我无法模拟 HttpContext.Current.Request.Files .我在Google上搜索了一些模拟工具,但也没有得到与 HttpContext.Current.Request.Files 的模拟相关的任何信息.请帮助我如何模拟它或为我的方法编写测试用例.

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.

推荐答案

您可以使用依赖注入,然后将HttpContextBase实例注入到该类中.假设您正在使用MVC:

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
    }
}

现在,您可以使用HttpContextBase的模拟实例化控制器.这就是您使用Moq的方式:

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
}

这篇关于模拟httpcontext.current.request.files的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆