在 System.Web.Services.WebService 中填充假的 HttpContext.Current.Application
我们正在尝试为旧的 .NET 4 Web 服务创建单元测试。 MCVE:
[WebService(Namespace = "http://somecompany.com/someservice/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RealService : System.Web.Services.WebService
{
private readonly int _key;
public RealService()
{
_key = (int)Application["appKey"];
}
}
这当然会崩溃,因为 Application
为 null。看来Application
是IIS提供的System.Web.HttpApplicationState
的一个实例。我们需要在 MSTest 而不是 IIS 中运行它。
幸运的是,Vadim Zozulya 的 FakeHttpContext
提供了一个假的 HttpContext
,包括 HttpApplicationState
:
using (new FakeHttpContext.FakeHttpContext())
{
HttpContext.Current.Application["appKey"] = 1831423222;
var rs = new RealService();
rs.ServiceToTest(testData);
}
虽然这会在 RealService
内创建一个 Application
实例,但它不会设置HttpApplicationState
; Application.Count
为零,Application["appKey"]
为 null。
我咨询了 Mocking HttpContext.Current.Application ,接受的答案也没有效果:
(new HttpContextWrapper(HttpContext.Current))["appKey"] = 1831423222;
也没有添加 Application[" appKey"]
。如何在 System.Web.Services.WebService
中填充假的 HttpContext.Current.Application
?
We're trying to create unit tests for an old .NET 4 web service. An MCVE:
[WebService(Namespace = "http://somecompany.com/someservice/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RealService : System.Web.Services.WebService
{
private readonly int _key;
public RealService()
{
_key = (int)Application["appKey"];
}
}
This of course crashes because Application
is null. It seems Application
is an instance of System.Web.HttpApplicationState
provided by IIS. We need to run this in MSTest, not IIS.
Fortunately, Vadim Zozulya's FakeHttpContext
provides a fake HttpContext
, including HttpApplicationState
:
using (new FakeHttpContext.FakeHttpContext())
{
HttpContext.Current.Application["appKey"] = 1831423222;
var rs = new RealService();
rs.ServiceToTest(testData);
}
While this creates an Application
instance inside RealService
, it does not set the HttpApplicationState
; Application.Count
is zero and Application["appKey"]
is null.
I consulted Mocking HttpContext.Current.Application and the accepted answer also has no effect:
(new HttpContextWrapper(HttpContext.Current))["appKey"] = 1831423222;
also does not add Application["appKey"]
. How do I populate a fake HttpContext.Current.Application
in System.Web.Services.WebService
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论