dimanche 3 février 2019

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?

Aucun commentaire:

Enregistrer un commentaire