单元测试Web服务 - 的HttpContext [英] Unit Testing Web Services - HttpContext
问题描述
我想写一个Web服务单元测试。我创建我的测试项目,参考我的Web项目(非服务引用,装配参考),然后写一些code测试Web服务 - 他们工作的罚款。不过,也有一些服务,确保通过使用到Web应用程序的用户登录 HttpContext.Current.User.Identity.IsAuthenticated
。
I want to write unit tests for a web service. I create my test project, reference my web project (not service reference, assembly reference), then write some code to test the web services - they work fine. However, there are some services which make sure the user is logged in to the web application by using HttpContext.Current.User.Identity.IsAuthenticated
.
在测试的背景下,有没有这样的东西的HttpContext,因此测试总是失败。这些类型的Web服务应该怎样进行单元测试?
In the context of the tests, there is no such thing as HttpContext, so the tests always fail. How should these kinds of web services be unit tested?
推荐答案
<一个href=\"http://stackoverflow.com/questions/524457/how-do-you-mock-the-session-object-collection-using-moq\">Here是一个相关的讨论。
我停下来引用 HttpContext.Current
直接。并使用这个类来代替:
I stopped referencing HttpContext.Current
directly. and use this class instead:
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;
}
}
和使用 HttpContextFactory.Current
而不是 HttpContext.Current
在我们的code。
and use HttpContextFactory.Current
instead of HttpContext.Current
in our code.
然后你写这在您的测试:
Then you write this in your test:
HttpContextFactory.SetCurrentContext(GetMockedHttpContext());
在这里GetMockedHttpContext()是的此处,看起来像这样:
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;
}
它采用了<一个href=\"http://stackoverflow.com/questions/64242/rhino-mocks-typemock-moq-or-nmock-which-one-do-you-use-and-why\">mocking框架的所谓起订量
在您的测试项目,你必须添加一个引用的System.Web
和 System.Web.Abstractions
,其中, HttpContextBase
定义。
In your test project you have to add a reference to System.Web
and System.Web.Abstractions
, where HttpContextBase
is defined.
这篇关于单元测试Web服务 - 的HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!