C# 模拟HttpContext.Current在NUnit测试中使用moq
我正在测试一个调用此类方法的MVC 3控制器:C# 模拟HttpContext.Current在NUnit测试中使用moq,c#,asp.net-mvc-3,nunit,moq,C#,Asp.net Mvc 3,Nunit,Moq,我正在测试一个调用此类方法的MVC 3控制器: public class SessionVar { /// <summary> /// Gets the session. /// </summary> private static HttpSessionState Session { get { if (HttpContext.Current == null)
public class SessionVar
{
/// <summary>
/// Gets the session.
/// </summary>
private static HttpSessionState Session
{
get
{
if (HttpContext.Current == null)
throw new ApplicationException
("No Http Context, No Session to Get!");
return HttpContext.Current.Session;
}
}
public static T Get<T>(string key)
{
return Session[key] == null ? default(T) : (T)Session[key];
}
...
}
当HttpContext.Current==null
我只需要会话对象“存在”,而不是会话上存储的实际值
你能告诉我我做错了什么吗
谢谢。从长远来看,如果为SessionVar类创建一个接口,您会更高兴。在运行时使用当前实现(通过依赖项注入)。在测试期间插入模拟。不再需要模拟所有这些Http运行时依赖项。HttpContext。会话属性中的当前值不受正在创建的模拟HttpContextBase的影响。也就是说,仅仅创建本地HttpContextBase并不会自动填充HttpContext.Current。事实上,HttpContext和HttpContextBase实际上并不相关。您必须使用HttpContextWrapper来统一它们 因此,最好将HttpContextWrapper实现传递到类SessionVar中。在下面的代码中,我将您的方法和属性更改为实例级别,以便我们可以在构造函数中设置上下文。如果没有上下文传递给构造函数,我们假设HttpContext.Current,但是您也可以为测试传递模拟实例
public class SessionVar
{
HttpContextWrapper m_httpContext;
public SessionVar(HttpContextWrapper httpContext = null)
{
m_httpContext = httpContext ?? new HttpContextWrapper(HttpContext.Current);
}
/// <summary>
/// Gets the session.
/// </summary>
private HttpSessionState Session
{
get
{
if (m_httpContext == null)
throw new ApplicationException("No Http Context, No Session to Get!");
return m_httpContext.Session;
}
}
public T Get<T>(string key)
{
return Session[key] == null ? default(T) : (T)Session[key];
}
...
}
公共类SessionVar
{
HttpContextWrapper m_httpContext;
公共会话变量(HttpContextWrapper httpContext=null)
{
m_httpContext=httpContext??新的HttpContextWrapper(httpContext.Current);
}
///
///获取会话。
///
私有HttpSessionState会话
{
得到
{
if(m_httpContext==null)
抛出新的ApplicationException(“没有Http上下文,没有要获取的会话!”);
返回m_httpContext.Session;
}
}
公共T获取(字符串键)
{
返回会话[key]==null?默认值(T):(T)会话[key];
}
...
}
这就是我最后要做的,不知何故,这感觉像是一个解决办法。。。但后来我发现其他人也这么做了,在你发表评论之后:变通的感觉几乎消失了:)我认为这也是一个很好的解决方案,但我更喜欢@PatrickSteele的,事实上,这就是我最后实现的解决方案。谢谢你的帮助。
CanRenderEmployeeListSystem.ApplicationException : No Http Context,
No Session to Get!
public class SessionVar
{
HttpContextWrapper m_httpContext;
public SessionVar(HttpContextWrapper httpContext = null)
{
m_httpContext = httpContext ?? new HttpContextWrapper(HttpContext.Current);
}
/// <summary>
/// Gets the session.
/// </summary>
private HttpSessionState Session
{
get
{
if (m_httpContext == null)
throw new ApplicationException("No Http Context, No Session to Get!");
return m_httpContext.Session;
}
}
public T Get<T>(string key)
{
return Session[key] == null ? default(T) : (T)Session[key];
}
...
}