简体   繁体   中英

xUnit test async event handler

I have a class that uses Azure Service Bus and it basically sends an email by putting a message to a queue. When I write an integration tests I need to make sure I can receive the message that's been sent (no, I'm not testing Service Bus). So, here's the code for that:

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

But when I run it I get an exception saying something like "There's no currently active test". What is the best way of dealing with this kind of tests?

You are testing Azure Service Bus in a way that you're sending a message on er the wire and receive it. Looking at the code, you want to verify message is contracted in a certain way. Rather than going through the whole send / receive phase, you could short-circuit it by just testing the Message constructed by your code. Alternatively, create a plugin to intercept the message just before it's sent. In case you insist on sending/receiving, your code must not exist until assertion is either executed or there's a timeout. And that's due to the fact that message handler is a synchronous API that will continue execution of the test method before the message has a change to be processed by the callback. await Task.Delay(TimeSpan.FromSeconds(5)) is not guaranteed to be sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM