C# xUnit测试异步事件处理程序
我有一个使用Azure服务总线的类,它基本上通过将消息放入队列来发送电子邮件。当我编写一个集成测试时,我需要确保我能够收到发送的消息。不,我不是在测试服务总线。下面是代码:C# xUnit测试异步事件处理程序,c#,azure,testing,azureservicebus,xunit,C#,Azure,Testing,Azureservicebus,Xunit,我有一个使用Azure服务总线的类,它基本上通过将消息放入队列来发送电子邮件。当我编写一个集成测试时,我需要确保我能够收到发送的消息。不,我不是在测试服务总线。下面是代码: [Fact] public async Task PutEmailIntoTheQueue() { IlgQueueEmailInfo actual = new IlgQueueEmailInfo("from@address.com", "to@address.com", "subje
[Fact]
public async Task PutEmailIntoTheQueue()
{
IlgQueueEmailInfo actual = new IlgQueueEmailInfo("from@address.com", "to@address.com", "subject", "test body", MessageBodyType.Text,
"email1@domain.com",
"email2@domain.com");
ServiceBusConnectionStringBuilder sbcb =
new ServiceBusConnectionStringBuilder(SERVICE_BUS_ENDPOINT_S, QUEUE_NAME_S, SAS_KEY_NAME, EMAIL_TESTS_SAS);
QueueClient receiveClient = new QueueClient(sbcb, ReceiveMode.ReceiveAndDelete);
bool hasBeenCalled = false;
//
// Check values here
//
async Task ReceiveMessageHandler(Message message, CancellationToken cancellationToken)
{
Output.WriteLine("Received Message\n");
Assert.True(message.Label != null && message.ContentType != null &&
message.Label.Equals(IlgEmailQueue.MESSAGE_LABEL_S, StringComparison.InvariantCultureIgnoreCase) &&
message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase));
byte[] body = message.Body;
string msgJson = Encoding.UTF8.GetString(body);
Output.WriteLine($"json: {msgJson}\n");
IlgQueueEmailInfo emailInfo = JsonConvert.DeserializeObject<IlgQueueEmailInfo>(msgJson);
Assert.NotNull(emailInfo);
Output.WriteLine("emailInfo is not NULL");
Assert.Equal(actual, emailInfo);
Output.WriteLine($"emailInfo equals to actual: {actual == emailInfo}\n");
Output.WriteLine("Setting hasBeenCalled to True");
hasBeenCalled = true;
await receiveClient.CompleteAsync(message.SystemProperties.LockToken);
}
receiveClient.RegisterMessageHandler(
ReceiveMessageHandler,
new MessageHandlerOptions(LogMessageHandlerException) {AutoComplete = true, MaxConcurrentCalls = 1});
await _emailQueue.QueueForSendAsync(actual.FromAddress, actual.ToAddresses[0], actual.Subj, actual.Body, MessageBodyType.Text, actual.CcAddress,
actual.BccAddress);
await Task.Delay(TimeSpan.FromSeconds(5));
Assert.True(hasBeenCalled);
}
但是当我运行它的时候,我得到了一个异常,说好像没有当前活动的测试。处理此类测试的最佳方法是什么?您正在测试Azure Service Bus,测试方式是通过er线发送消息并接收消息。查看代码,您希望验证消息是否以某种方式收缩。您不必经历整个发送/接收阶段,只需测试代码构造的消息即可缩短发送/接收阶段。或者,在消息发送之前创建一个插件来截获消息。若您坚持发送/接收,则在执行断言或超时之前,您的代码不得存在。这是因为消息处理程序是一个同步API,它将在回调处理消息更改之前继续执行测试方法。wait Task.DelayTimeSpan.FromSeconds5不一定足够。谢谢您的回复。我对任何云的经验都是,应该在集成测试中真正使用它。否则你会得到惊喜。是的,5秒可能不够,但这不是问题所在。我在考虑类似于jasmine.js的东西,以及它所做的工作。您正在测试元数据。ASB在发送您的邮件时不会更改它。2.你只是通过简单的读回来测试身体。同样,ASB不会改变它。那么通过电线发送的价值是什么呢?好吧,也许你是对的,而我现在所做的是过火了。。。但我仍然有疑问:如果您的代码发送消息,而您使用MessageReceiver检索它,有什么值得怀疑的?也许我遗漏了什么,但你在练习ASB和信息检索。