在 System.Web.Services.WebService 中填充假的 HttpContext.Current.Application

发布于 2025-01-12 00:18:52 字数 1503 浏览 1 评论 0原文

我们正在尝试为旧的 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文