在C#中测试异步事件处理程序

时间:2017-01-30 10:20:32

标签: c# unit-testing asynchronous event-handling

我有一个异步事件处理程序,它处理消息并在所有消息处理完成后在主线程上引发事件MessageReceived,即

private async void OnMessageReceived(object sender, Brokered msg)
{
    await Task.Run(() => {
        var newMsg = msg.GetBody<string>();
        // Long running code to process message...

        Application.CurrentDispatcher.BeginInvoke((Action)(() =>
        {
          MessageReceived?.Invoke(this, newMsg);
        }));
    });
 }

现在我想写一个单元测试(NUnit)来检查事件是否被引发,比如

[Test]
public void MessageService_ShimRaisesMessageReceived_RaisesMessageReceived()
{
   // Arrange
   var msg = "This is a test message";
   var brokeredMsg = new BrokeredMessage(msg);

   var isFired = false;
   _messageService.MessageReceived += (sender, args) =>  {isFired = true; };

   // Act
   _serviceBusShim.MessageReceived += Raise.Event<EventHandler<BrokeredMessage>>(this, brokeredMsg);

   // Assert
   Assert.That(isFired, Is.True);
}

但是,上述测试将失败,因为测试尝试在EventHandler中的Task运行之前进行断言。如何使用NUnit正确设置测试,以便测试在Assert发生之前等待Task运行。

0 个答案:

没有答案