单元测试CorrelationId与Rebus

时间:2018-06-06 13:19:23

标签: rebus

假设我有Handler,如下所示:

public async Task Handle(Message message)
{
    Guid correlationId = GetCorrelationId();

    var newMessage = new MessageReceived
    {
        horse = message.Horse,
        correlationId = correlationId
    };
}

private static Guid GetCorrelationId()
{
    if (!MessageContext.Current.Headers.TryGetValue("rbs2-corr-id", out string correlationId))
    {
        throw new ArgumentException();
    }

    if (!Guid.TryParse(correlationId, out Guid correlationIdGuid))
    {
        throw new ArgumentException();
    }

    return correlationIdGuid;
}

我如何进行单元测试呢?我目前有一个(显然是错误的)测试,我只是设置一个MessageReceived对象并将其传递给Handle,但当然它在GetCorrelationId处失败,因为没有实际{ {1}}。我是否必须设置MessageContext并以某种方式使用它?

1 个答案:

答案 0 :(得分:1)

不是通过静态IMessageContext属性访问当前MessageContext.Current,而应将其注入到处理程序的构造函数中,如下所示:

public class MyHandler : IHandleMessages<Message>
{
    public MyHandler(IMessageContext messageContext)
    {
        this.messageContext = messageContext;
    }

    public async Task Handle(Message message)
    {
        Guid correlationId = GetCorrelationId(messageContext);

        var newMessage = new MessageReceived
        {
            horse = message.Horse,
            correlationId = correlationId
        };
    }

    static Guid GetCorrelationId(IMessageContext messageContext)
    {
        if (!messageContext.Headers.TryGetValue("rbs2-corr-id", out string correlationId))
        {
            throw new ArgumentException();
        }

        if (!Guid.TryParse(correlationId, out Guid correlationIdGuid))
        {
            throw new ArgumentException();
        }

        return correlationIdGuid;
    }
}

这将使您在测试期间实现伪造的消息上下文变得容易:)