0
votes

I have a Java project that is using some Azure Functions like HttpTrigger and a QueueTrigger. I used azure-fucntions-quickstart archetype to generate this project so it can with some boilerplate code for the HttpTrigger and a Unit Test for it, but nothing for the QueueTrigger. I am trying to get help to write a good unit test for this QueueTrigger, which is essentially reading messages (popping) off a queue. The code for the queue looks something like this:

@FunctionName("queuehandler")
    public void dequeue(
        @QueueTrigger(name="qmsg", queueName=QUEUE_NAME, connection=QUEUE_CONNECTION) String qmsg,  // this is the event message
        @BindingName("DequeueCount") int count,  // number of times this message has been popped off the stack.
        @BindingName("ExpirationTime") Date expireTime // time it will expire
    )
    {

        log.info("Queue Receive {} DequeueCount:{} Expires:{}", qmsg, count, expireTime);

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        try
        {
            EventGridEvent event = convertStringMsgToEventJSON(qmsg);
            MyClass.getInstance().handle(event);
        }
        catch(Exception ex)
        {
            log.error("Error handling queue dequeue count: {}, expires: {}, qmessage", count, expireTime, qmsg, ex);
            // Throwing an exception will cause the queue to retry this message again.
            // as per host.json, every failed message is retried for maximum of 3 times with an interval of 3 minutes
            throw ex;
        }
        finally
        {
            sw.stop();
            log.info("time it took to handle queue message: {}", sw.toString());
        }
    }

Can anyone recommend a standard Unit Test for this queue trigger azure function? For example , it looks like the Boierplate HttpTrigger test just passes a request with parameters "name" and "azure" and empty body and calls an assertEquals to make status of the request is a 200 or ok.

1

1 Answers

1
votes

This would be simpler if Azure Functions supported DI in Java, but as things stand what you probably want to do is to extract the body of the Function out to a separate method that accepts an instance of MyClass. Then you can test that method rather than the Function itself. When testing, pass in a mock of MyClass and assert that handle() is called, and in the actual Function just call it with MyClass.getInstance().