简体   繁体   English

定时器触发单元测试 Azure Function:提供测试数据

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

To Unit Testing HTTP triggered Azure Functions with test data is well and often described. To Unit Testing HTTP triggered Azure Functions with test data 很好并且经常描述。 For example here: How to write unit test for azure function v1例如这里: How to write unit test for azure function v1

Mock data are given in the http request.模拟数据在 http 请求中给出。

But I have a timer triggerd Azure function which reads data from a FTP server.但我有一个计时器触发 Azure function 从 FTP 服务器读取数据。 I would like to Unit Test the function with test data.我想用测试数据对 function 进行单元测试。

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

a running Unit Test function to test the logger, just to show how I started:运行单元测试 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() return a list of objects. serviceClass.getOrdersFromFtp() 返回一个对象列表。 I could create this list with mock data in the unit test but how to give it to the timer triggered azure function?我可以在单元测试中使用模拟数据创建此列表,但如何将其提供给触发的计时器 azure function?

You should move your business logic outside of the azure function and test that, rather than coming up with ways to mock data for a timer-triggered function.您应该将您的业务逻辑移到 azure function 之外并对其进行测试,而不是想出为计时器触发的 function 模拟数据的方法。

Your code would look something like this:您的代码看起来像这样:

[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