0

这应该很简单,我可能遗漏了一些东西。我在这里工作:http: //support.nservicebus.com/customer/portal/articles/856297-unit-testing

以下总是失败:

[TestFixture]
public class MyTestFixture
{
    [Test]
    public void RoundTrip() {
        Test.Initialize();

        var correlationId = Guid.NewGuid();
        Test.Handler(bus => new MyHandler(bus))
            .ExpectReply<IEventThatHappened>(m => m.CorrelationId == correlationId)
            .OnMessage<MyCommand>(m => new MyCommand(correlationId));
    }

}

public interface IEventThatHappened : IEvent
{
    Guid CorrelationId { get; set; }
}

public class MyCommand : ICommand
{
    public Guid CorrelationId { get; private set; }

    public MyCommand(Guid correlationId) {
        CorrelationId = correlationId;
    }
}

public class MyHandler : IHandleMessages<MyCommand>
{
    private readonly IBus _bus;

    public MyHandler(IBus bus) {
        if (bus == null) {
            throw new ArgumentNullException("bus");
        }
        _bus = bus;
    }

    public void Handle(MyCommand message) {
        _bus.Send<IEventThatHappened>(m => m.CorrelationId = message.CorrelationId);
    }
}

如果我在处理程序中设置断点,则 message.CorrelationId == Guid.Empty。测试过程中抛出的异常是:

System.Exception:ExpectedReplyInvocation 未完成。调用:SendInvocation

我尝试过使用 bus.Send、bus.Publish、bus.Reply ,但每一个都因相应的 Expected*Invocation 而失败。

为什么是 message.CorrelationId == Guid.Empty 而不是我提供的值?为什么 Test.Handler<> 没有检测到我在处理程序中调用了 Send/Reply/Publish?

注意:使用 Nuget 的 NServiceBus 3.3。

4

2 回答 2

1

这里有几个问题。

  1. 在您的处理程序中,您正在尝试Bus.Send()一个事件(IEventThatHappened实现IEvent,甚至被命名为事件),这是不允许的。命令已发送,事件已发布。
  2. 您的测试正在使用ExpectReply,如果处理程序正在执行您所期望的Bus.Reply()。假设您修复了 #1,我相信您会寻找.ExpectPublish().

所以首先你需要弄清楚你真正想要做什么!

于 2013-04-30T18:48:09.300 回答
0

你需要Reply代替Send!

这是通过的测试:

[TestFixture]
public class MyTestFixture
{
    [Test]
    public void RoundTrip()
    {
        Test.Initialize();

        var correlationId = Guid.NewGuid();
        var myCommand = new MyCommand(correlationId);

        Test.Handler(bus => new MyHandler(bus))
            .ExpectReply<IEventThatHappened>(m => m.CorrelationId == correlationId)
            .OnMessage(myCommand);
    }

}

public interface IEventThatHappened : IEvent
{
    Guid CorrelationId { get; set; }
}

public class MyCommand : ICommand
{
    public Guid CorrelationId { get; private set; }

    public MyCommand(Guid correlationId)
    {
        CorrelationId = correlationId;
    }
}

public class MyHandler : IHandleMessages<MyCommand>
{
    private readonly IBus _bus;

    public MyHandler(IBus bus)
    {
        if (bus == null)
        {
            throw new ArgumentNullException("bus");
        }
        _bus = bus;
    }

    public void Handle(MyCommand message)
    {
        _bus.Reply<IEventThatHappened>(m => m.CorrelationId = message.CorrelationId);
    }
}
于 2013-04-29T23:14:46.000 回答