xUnit测试异步事件处理程序

时间:2019-02-03 20:38:15

标签: c# azure testing azureservicebus xunit

我有一个使用Azure Service Bus的类,它基本上是通过将消息放入队列来发送电子邮件的。在编写集成测试时,我需要确保可以接收到已发送的消息(不,我没有测试Service Bus)。因此,这是该代码:

    [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);
    }

但是当我运行它时,出现一个异常,例如“当前没有活动的测试”。处理此类测试的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您正在以一种通过有线方式发送消息并接收消息的方式来测试Azure Service Bus。查看代码,您想验证消息是否以某种方式收缩。您可以通过测试代码构造的Message来缩短整个发送/接收阶段的时间,而不是将其短路。或者,创建一个插件以在消息发送之前拦截消息。如果您坚持要发送/接收,则在执行断言或超时之前,代码必须不存在。这是因为消息处理程序是一个同步API,它将继续执行测试方法之前,消息具有要由回调处理的更改。 await Task.Delay(TimeSpan.FromSeconds(5))不能保证足够。