我有一个Java项目正在使用一些Azure函数,例如HttpTrigger和QueueTrigger。我使用azure-fucntions-quickstart
原型来生成此项目,因此它可以为HttpTrigger提供一些样板代码并为其进行单元测试,但对于QueueTrigger没有任何帮助。我正在努力寻求帮助,以便为此QueueTrigger编写一个好的单元测试,它实质上是从队列中读取消息(弹出)。队列的代码如下所示:
@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());
}
}
有人可以为此队列触发天蓝色功能推荐标准的单元测试吗?例如,看起来Boierplate HttpTrigger测试只是传递了一个参数为“ name”和“ azure”且为空的请求,并调用assertEquals
以使该请求的状态为200
或{{ 1}}。
答案 0 :(得分:1)
如果Azure Functions在Java中支持DI,这会更简单,但是就目前情况而言,您可能要做的是将Function的主体提取到接受MyClass
实例的单独方法中。然后,您可以测试该方法,而不是功能本身。在测试时,传递MyClass
的模拟并断言handle()
被调用,而在实际的Function中,只需使用MyClass.getInstance()
对其进行调用。