簡體   English   中英

定時器觸發單元測試 Azure Function:提供測試數據

[英]Unit Tests for timer triggered Azure Function: provide test data

To Unit Testing HTTP triggered Azure Functions with test data 很好並且經常描述。 例如這里: How to write unit test for azure function v1

模擬數據在 http 請求中給出。

但我有一個計時器觸發 Azure function 從 FTP 服務器讀取數據。 我想用測試數據對 function 進行單元測試。

我的function:

[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();
...

運行單元測試 function 來測試記錄器,只是為了展示我是如何開始的:

public void TestLogger()
{
    // https://learn.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 function?

您應該將您的業務邏輯移到 azure function 之外並對其進行測試,而不是想出為計時器觸發的 function 模擬數據的方法。

您的代碼看起來像這樣:

[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();
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM