ASP.NET Core 单元测试:如何 Mock HttpContext.Features.Get()

点击上方蓝字关注“汪宇杰博客”

导语

在 ASP.NET Core 里,如果你想单元测试 HttpContext.Features.Get<SomeType>(),这个技巧一定不要错过。

问题

我有个 Error 页面,需要取得异常的详细信息。我使用 HttpContext.Features.Get<IExceptionHandlerPathFeature>() 方法。

public void OnGet()

{

    var requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;

    var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

    if (exceptionFeature is not null)

    {

        // Get which route the exception occurred at

        var routeWhereExceptionOccurred = exceptionFeature.Path;

        // Get the exception that occurred

        var exceptionThatOccurred = exceptionFeature.Error;

        _logger.LogError($"Error: {routeWhereExceptionOccurred}, " +

                         $"client IP: {HttpContext.Connection.RemoteIpAddress}, " +

                         $"request id: {requestId}", exceptionThatOccurred);

    }

    RequestId = requestId;

}

现在,我需要单元测试这段代码。通常,在需要 HttpContext的 Page 或 Controller 中,我会使用 DefaultHttpContext 的实例。但我发现 HttpContext 上的 Features 属性是只读的。因此没有办法将 mock 好的对象赋值给它。

namespace Microsoft.AspNetCore.Http

{

    public abstract class HttpContext

    {

        protected HttpContext();

        //

        // Summary:

        //     Gets the collection of HTTP features provided by the server and middleware available

        //     on this request.

        public abstract IFeatureCollection Features { get; }

        //  ...

    }

}

解决办法

首先,像平常一样准备 mock。在我的案例里,我需要配置 IFeatureCollection.Get() 方法,返回我想要的对象。

var mockIFeatureCollection = _mockRepository.Create<IFeatureCollection>();

mockIFeatureCollection.Setup(p => p.Get<IExceptionHandlerPathFeature>())

    .Returns(new ExceptionHandlerFeature

    {

        Path = "/996/icu",

        Error = new("Too much fubao")

    });

httpContextMock.Setup(p => p.Features).Returns(mockIFeatureCollection.Object);

下下来,为了给 HttpContext.Features 赋值,我们这次不能使用 DefaultHttpContext 了。我们需要创建 HttpContext 自己的 mock,并且配置 Features 属性返回刚才 mock 的 IFeatureCollection 对象。

var httpContextMock = _mockRepository.Create<HttpContext>();

httpContextMock.Setup(p => p.Features).Returns(mockIFeatureCollection.Object);

现在运行单元测试,我们可以看到正确的值已经输出了。

汪宇杰博客

Azure | .NET | 微软 MVP

无广告,不卖课,做纯粹的技术公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值