Here là cuộc thảo luận liên quan.
Tôi đã ngừng tham chiếu HttpContext.Current
trực tiếp. và sử dụng lớp này để thay thế:
public class HttpContextFactory
{
private static HttpContextBase m_context;
public static HttpContextBase Current
{
get
{
if (m_context != null)
return m_context;
if (HttpContext.Current == null)
throw new InvalidOperationException("HttpContext not available");
return new HttpContextWrapper(HttpContext.Current);
}
}
public static void SetCurrentContext(HttpContextBase context)
{
m_context = context;
}
}
và sử dụng HttpContextFactory.Current
thay vì HttpContext.Current
trong mã của chúng tôi.
Sau đó, bạn viết những dòng này trong thử nghiệm của bạn:
HttpContextFactory.SetCurrentContext(GetMockedHttpContext());
nơi GetMockedHttpContext() là từ here và trông như thế này:
private System.Web.HttpContextBase GetMockedHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(x => x.Identity).Returns(identity.Object);
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns("test");
return context.Object;
}
Nó sử dụng một mocking framework gọi moq
Trong của bạn dự án thử nghiệm bạn phải thêm tham chiếu đến System.Web
và System.Web.Abstractions
, nơi HttpContextBase
được xác định.
Tôi cũng đã bắt đầu thực hiện việc này (thay thế HttpContext bằng HttpContextFactory), và nó thực sự giúp với Kiểm thử Đơn vị (Tôi đã gói các khả năng này trong một API mà bạn có thể xem tại đây http://o2platform.wordpress.com/2011/ 04/05/mocking-httpcontext-httprequest-and-httpresponse-cho-unittests-using-moq /) –
Tôi không sử dụng moq, do đó, điều này đã không làm cho tôi đến 100%, nhưng nó đã được hữu ích. Tôi nhìn vào các vật giả giả của Stephen Walther để được giúp đỡ: http://stephenwalther.com/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx –