简体   繁体   中英

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.

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

use Moq;

...

...

var log = new Mock(TraceLevel.Info).Object;

Simple!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM