【问题标题】:The source is not working when use mock in unit test project在单元测试项目中使用模拟时源不工作
【发布时间】:2012-09-25 08:53:13
【问题描述】:

当我在单元测试项目中使用模拟概念初始化 httpcontext.Request.Url 时,源项目未初始化。所以它抛出空引用异常。请告诉我如何解决这个问题?

例如:

实际代码

class sample

{
    public void sample_method()
    {
        string url=Request.Url.ToString();
    }
}

更新了单元测试代码

​

class sample: IRequestAttr
{
    private readonly IRequestAttr _attr;

    public sample(IRequestAttr attr)
    {
        _attr=attr;
    }

    public string URL
    {
        return HttpContext.Request.Url.ToString();
    }

    public void sample_method()
    {
        string url=_attr.URL();
    }
}

public interface IRequestAttr
{
    string URL();
}

【问题讨论】:

    标签: asp.net-mvc unit-testing


    【解决方案1】:

    您是否尝试过使用

    HttpContextBase
    

    创建一个工厂来获取您的上下文,您可以在其中将真实请求替换为您想要的任何模拟。可根据要求提供更多代码

    查看我自己的测试中的笔记,我为一个解释得很好的博客添加了书签 http://www.codethinked.com/Using-SystemWebAbstractions-in-Your-WebForms-Apps

    【讨论】:

      猜你喜欢
      • 2023-02-24
      • 2023-03-03
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多