我正在尝试集成测试某些RabbitMQ代码。现在,我有一个类RabbitMqConsumer
和一个BeginConsuming()
方法,如下所示:
public void BeginConsuming()
{
var messageConsumer = new EventingBasicConsumer(ConsumerChannel);
//Consumes messages from queue
messageConsumer.Received += (model, eventArgs) =>
{
var message = Encoding.UTF8.GetString(eventArgs.Body);
HandleMessage(message);
// Send a message to the stats service to recalculate the stats when each game ends
if (GameplayMessageHandler.GetMessageType(message) == "gameEnd")
{
var jsonMsgObject = (JObject)JsonConvert.DeserializeObject(message);
var gameGuid = (Guid) jsonMsgObject["game_guid"];
SendPostGameStatsEventToStatsService(gameGuid);
}
// After *everything* is done for processing this message, fire the message handled event
MessageHandled?.Invoke();
};
ConsumerChannel.BasicConsume(
queue: _rabbitSettings.GamesQueueName,
autoAck: true,
consumer: messageConsumer);
Log.Logger.Information("Now consuming RabbitMq messages in channel: {queueName}", _rabbitSettings.GamesQueueName);
}
我在该类中声明了以下事件/委托:
public delegate void OnMessageHandledListener();
public event OnMessageHandledListener MessageHandled;
这个想法是当RabbitMQ处理完每条消息时触发此事件。然后,我可以编写一个如下所示的测试:
model.BasicPublish("", "GameEvents", false, null, msgBytes);
Assert.True(fakeRabbitServer.Queues["GameEvents"].Messages.Count.Equals(1));
gameEventsRabbitConsumer.MessageHandled += () =>
{
Assert.True(fakeRabbitServer.Queues["GameEvents"].Messages.Count.Equals(0));
};
gameEventsRabbitConsumer.BeginConsuming();
但是,此测试在Assert.True(fakeRabbitServer.Queues["GameEvents"].Messages.Count.Equals(0));
行上失败
为什么此时我的队列没有排空?这是我处理事物的异步性质时的错误吗?我该如何纠正?