Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Azure Function: Cannot create an instance of TraceWriter, how to mock?

I'm trying to unit test a basic Azure Function. The function's Run method requires a TraceWriter argument; TraceWriter is an abstract class and I'm not finding much in terms of documentation for mocking this dependency.

Here's the signature of the method I'm attempting to test:

public static void Run(string myQueueItem, TraceWriter log)

Any insights regarding mocking TraceWriter and/or Azure Function unit testing strategies would be much appreciated.

like image 747
JTW Avatar asked May 16 '17 19:05

JTW


People also ask

How do you mock an azure function?

In the Azure portal, you navigate to your Function App and select a function. Click proxies in the chosen function and create a new proxy. Next, you provide a name, route template, allowed HTTP methods, and for example choose to override the response when the function is invoked.

Can you unit test Azure functions?

Azure Functions are small pieces of code you can run in the cloud. Even with these little pieces of code, you should create unit tests. Since it is a small piece of code, you need to test creating a unit test, which is not too difficult or time-consuming.

What is mock test in C#?

Mocking is a process that allows you to create a mock object that can be used to simulate the behavior of a real object. You can use the mock object to verify that the real object was called with the expected parameters, and to verify that the real object was not called with unexpected parameters.

What is unit testing in Azure?

Introduction. TLTR: Create Azure DevOps git project using azure-pipelines.yml, create build artifact, deploy ADFv2 and SQLDB bacpac, trigger pytest to do unit tests. Unit testing is a software engineering practice that focuses on testing individual parts of code.


1 Answers

Azure Functions now can support consuming an ILogger as per this GitHub thread: https://github.com/Azure/Azure-Functions/issues/293


My suggestion would be that you use the new tooling supported in VS2017 Preview with precompiled functions to allow you to improve your function's testability. You can get started with the new tools for Azure Functions here:

https://blogs.msdn.microsoft.com/appserviceteam/2017/03/16/publishing-a-net-class-library-as-a-function-app/

Donna Malayeri has published an excellent post that explains how to use precompiled Functions with C#: https://blogs.msdn.microsoft.com/appserviceteam/2017/03/16/publishing-a-net-class-library-as-a-function-app/

This will allow you to create a Function that consumes an Interface instead of the concrete object. The answer is a bit long winded but there's a similar thread here with a nice answer:

Azure Function logging using TraceWriter in external library

ILogger

like image 76
Chris Avatar answered Oct 06 '22 01:10

Chris