对于单元测试很好并且经常描述带有测试数据的HTTP触发的Azure函数。例如这里: 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函数?
答案 0 :(得分: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();
...