使用自定义处理程序测试 NServiceBus 行为

Testing NServiceBus Behavior with custom Handler

我有一个带有自定义属性的 MessageHandler。我正在测试的行为根据该属性的值执行某些操作。 The NServicebus documentation 仅提供基于模拟处理程序的行为的单元测试示例。我怎样才能使用自己的假货,或者有其他方法可以测试我的行为吗?

// A fake message handler containing the attribute
[ExecuteHandler(true)]
class FakeHandler : IHandleMessages<FakeCommand>
{
  public Task Handle(FakeCommand message, IMessageHandlerContext context) => Task.CompletedTask;
}

[Test]
public async Task Invoke_GivenHandlerWithoutAttribute_InvokeNext()
{
  // Given
  var handlerExecuted = false;
  var context = new TestableMessageHandlerContext
  {
    // I want to add my fake handler to the context so I can test if it gets executed. Problem is that I can't cast my handler to type MessageHandler
    // MessageHandler = new FakeHandler(),
  }

  // When
  await _behavior.Invoke(context, () =>
  {
    handlerExecuted = true;
    return Task.CompletedTask;
  });

  // Then
  handlerExecuted.Should().BeTrue();
}

回答我自己的问题。我通过让我的处理程序继承 MessageHandler.

使其工作
[Test]
public async Task Invoke_GivenHandlerWithAttributeTrue_InvokeNext()
{
  // Given
  var handlerExecuted = false;
  var context = new TestableMessageHandlerContext
  {
    MessageHandler = new MessageHandler(null, typeof(FakeHandler)),
  }
  
  // When
  await _behavior.Invoke(context, () =>
  {
    handlerExecuted = true;
    return Task.CompletedTask;
  });

  // Then
  handlerExecuted.Should().BeTrue();
}

[Test]
public async Task Invoke_GivenHandlerWithAttributeFalse_DoesNotInvokeNext()
{
  // Given
  var handlerExecuted = false;
  var context = new TestableMessageHandlerContext
  {
    MessageHandler = new MessageHandler(null, typeof(FakeHandlerNotExecuting)),
  }
  
  // When
  await _behavior.Invoke(context, () =>
  {
    handlerExecuted = true;
    return Task.CompletedTask;
  });

  // Then
  handlerExecuted.Should().BeFalse();
}
[ExecuteHandler(true)]
class FakeHandler: IHandleMessages<FakeCommand>
{
  public Task Handle(FakeCommand message, IMessageHandlerContext context) => Task.CompletedTask;
}
[ExecuteHandler(false)]
class FakeHandlerNotExecuting: IHandleMessages<FakeCommand>
{
  public Task Handle(FakeCommand message, IMessageHandlerContext context) => Task.CompletedTask;
}