我正在为我的mvc应用程序进行单元测试。它包括许多类库。我已经使用NSubstitute模拟了单元测试项目中的http上下文并创建了cookie。但是在调试源代码时,它在类库中不可用。我们如何在类库中获取cookie?
单元测试
[Test]
[TestModule(ModuleAttribute.ModuleName)]
public void MethodName()
{
var httpContext = MockHttphelpers.MockHttpContextBaseWithUrlReferrer("~/pagename", "https://test.abc.com");
var checkSecureConn = httpContext.Request.IsSecureConnection;
var userCookie = new HttpCookie("TrackReferrer");
userCookie.Value = "http://www.google.com,http://test.abc.com";
userCookie.Secure = true;
userCookie.HttpOnly = true;
httpContext.Request.Cookies.Add(userCookie);
this.TrackingInfo.GetCustomerOriginReferral();
Assert.AreEqual(httpContext.Session["sessionname"].ToString(), "www.google.com");
}
课程库
public void GetReferral()
{
string urlReferrer = HttpContext.Current.Request.UrlReferrer == null ? string.Empty : HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
if (!string.IsNullOrEmpty(urlReferrer) && new Uri(urlReferrer).Host != HttpContext.Current.Request.Url.Host && HttpContext.Current.Request.Cookies["TrackReferrer"] != null && !string.IsNullOrEmpty(HttpContext.Current.Request.Cookies["TrackReferrer"].Value))
{
//Code
}
}
HttpContext Mock
public static HttpContextBase MockHttpContextBase()
{
var httpContextBase = Substitute.For<HttpContextBase>();
var httpRequestBase = Substitute.For<HttpRequestBase>();
var httpResponseBase = Substitute.For<HttpResponseBase>();
var httpSessionStateBase = Substitute.For<HttpSessionStateBase>();
var httpServerUtilityBase = Substitute.For<HttpServerUtilityBase>();
httpRequestBase.Cookies.Returns(new HttpCookieCollection());
httpResponseBase.Cookies.Returns(new HttpCookieCollection());
httpRequestBase.ServerVariables.Returns(MockRequestObjects.ServerVariables);
httpContextBase.Request.Returns(httpRequestBase);
httpContextBase.Response.Returns(httpResponseBase);
httpContextBase.Session.Returns(httpSessionStateBase);
httpContextBase.Server.Returns(httpServerUtilityBase);
// Initializing HttpContext.Current
HttpContext.Current = MockHttpContext();
HttpContext.Current.Request.Browser = new HttpBrowserCapabilities() { Capabilities = new Dictionary<string, string> { { "supportsEmptyStringInCookieValue", "false" } } };
// Initializing Session in HttpContextBase in ControllerContext
httpContextBase.Session.Returns(MockHttpContextControllerContextSession());
// Initializing ApplicationInstance in HttpContextBase in ControllerContext
httpContextBase.ApplicationInstance = new HttpApplication();
// Initializing ApplicationInstance in HttpContext.Current
HttpContext.Current.ApplicationInstance = new HttpApplication();
httpContextBase.Request.ServerVariables.Returns(MockRequestObjects.ServerVariables);
// Initializing FormCollection in HttpContextBase in ControllerContext
httpContextBase.Request.Form.Returns(new FormCollection());
return httpContextBase;
}