【问题标题】:Unit Tests for timer triggered Azure Function: provide test data计时器触发 Azure 功能的单元测试:提供测试数据
【发布时间】:2020-10-11 10:26:45
【问题描述】:

使用测试数据对 HTTP 触发的 Azure Functions 进行单元测试已得到很好的描述,并且经常被描述。例如这里: How to write unit test for azure function v1

模拟数据在http请求中给出。

但是我有一个定时器触发的 Azure 函数,它从 FTP 服务器读取数据。我想用测试数据对函数进行单元测试。

我的功能:

[FunctionName("MyTimerTriggeredFunction")]
public static void Run([TimerTrigger("0 */2 * * * *")]TimerInfo myTimer, ILogger log, ExecutionContext context)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

    ServiceClass serviceClass = new ServiceClass(log, context);

    List<Order> orderList = serviceClass.getOrdersFromFtp();
...

一个正在运行的单元测试函数来测试记录器,只是为了展示我是如何开始的:

public void TestLogger()
{
    // https://docs.microsoft.com/de-de/azure/azure-functions/functions-test-a-function
    var logger = (ListLogger)TestFactory.CreateLogger(LoggerTypes.List);
    MyTimerTriggeredFunction.Run(null, logger, null);
    var msg = logger.Logs[0];
    bool testString = msg.Contains("C# Timer trigger function executed at");
    Assert.IsTrue(testString);
}

serviceClass.getOrdersFromFtp() 返回一个对象列表。我可以在单元测试中使用模拟数据创建此列表,但如何将其提供给计时器触发的 azure 函数?

【问题讨论】:

    标签: c# unit-testing azure-functions mstest


    【解决方案1】:

    您应该将业务逻辑移到 azure 函数之外并对其进行测试,而不是想出方法来模拟计时器触发函数的数据。

    您的代码将如下所示:

    [FunctionName("MyTimerTriggeredFunction")]
    public static void Run([TimerTrigger("0 */2 * * * *")]TimerInfo myTimer, ILogger log, ExecutionContext context)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    
        ServiceClass serviceClass = new ServiceClass(log, context);
    
        serviceClass.DoWork();
    
    ...
    
    class ServiceClass
    {
        public void DoWork()
        {        
             List<Order> orderList = serviceClass.getOrdersFromFtp();
    ...
    

    【讨论】:

    • ...我想我必须了解单元测试和集成测试之间的区别。
    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多