如何为 CorrelationId 模拟 ICorrelationContextAccessor

How to mock ICorrelationContextAccessor for CorrelationId

对于模拟,我使用的是 Moq 4.16.1 包。

我有一个派生自 DelegatingHandler class

的 class
public class Handler : DelegatingHandler
{
  private readonly ICorrelationContextAccessor _correlationContextAccessor;
  public Handler(ICorrelationContextAccessor correlationContextAccessor)
        {
            _correlationContextAccessor = correlationContextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
        {
                request.Headers.Add("x-correlation-Id", _correlationContextAccessor.CorrelationContext.CorrelationId);

                var response = await base.SendAsync(request, ct);

                response.EnsureSuccessStatusCode();

                return response;
        }
}

现在我需要模拟 ICorrelationContextAccessor。

我试过下面的代码,但没有成功

_correlationContextAccessor.SetupProperty(x => x.CorrelationContext.CorrelationId, new Guid().ToString());

有人知道如何在这种情况下模拟 CorrelationId 吗?

CorrelationContext 的源代码中,你不能模拟 CorrelationId 属性 因为它是一个只读 属性.

还有另一种方法你可以尝试使用它,尝试通过SetupProperty方法使用mock CorrelationContext 属性,然后创建一个你期望的实例Guid

var guid = new Guid().ToString();
_correlationContextAccessor.SetupProperty(x => x.CorrelationContext, new CorrelationContext(guid,"x-correlation-Id"));