Mocking FunctionContext in Azure blob trigger function unit tests in .net 8

50 views Asked by At

I need help with below .net testing.

We have existing unit tests for blobtrigger functions.

I upgraded to .net 8 and FunctionContext had to be in place of ExecutionContext to allow using RetryContext. This upgrade meant replacing Microsoft.Azure.Webjobs with Microsoft.Azure.Function.Worker .

The current unit test for the above blob trigger execute method is creating a new ExecutionContext object and setting the RetryContext.retryCount and RetryContext.maxRetryCount as needed for the tests. These 2 variables are used in checking the below condition,

if RetryContext.retryCount = RetryContext.maxRetryCount then file needs to be moved to a different folder that will later be handled.

The way our unit tests are written, all the test methods related to blobtrigger like fileUpload, executeInvalidFileName, etc., are setting a context object with these retrycontext properties and passing the context to execute method.

FunctionContext and Retrycontext are both abstract classes. RetryContext is a property of FunctionContext and it is a readonly property. I am unable to create an object and pass as context because FunctionContext is an abstract class.

I am not sure if mocking is the best way to handle this but I tried to mock the function context.

Please help me fix this to pass the context for my unit test.

My function is,

public async Task Run(string blobname, blobcontent, ExecutionContext context)
{
    await this.controller.execute(name,blob,context);
}

FunctionContext mock I created:

protected FunctionContext GetExecutionContextNotAtMaxRetry()
{
    var contextMoq = new Mock<FunctionContext>();
    contextMoq.Setup(X => X.RetryContext.RetryCount).Returns(1);
    contextMoq.Setup(X => X.RetryContext.MaxRetryCount).Returns(2);
    return contextMoq;
}

This is giving me an error as contextMoq is not same as FunctionContext.

Error is

Cannot implicitly convert type
Moq.Mock<Microsoft.Azure.Function.Worker.FunctionContext> to
Microsoft.Azure.Function.Worker.FunctionContext.
1

There are 1 answers

2
Mark Seemann On

If the error message, which I suppose is a compiler error, is

Cannot implicitly convert type
Moq.Mock<Microsoft.Azure.Function.Worker.FunctionContext> to
Microsoft.Azure.Function.Worker.FunctionContext.

then it tells you straight up with the problem is. Mock<FunctionContext> is not the same type as FunctionContext. Yet, the method GetExecutionContextNotAtMaxRetry is declared to return an object of the type FunctionContext, but the code returns a Mock<FunctionContext>.

Try changing the return value:

protected FunctionContext GetExecutionContextNotAtMaxRetry()
{
    var contextMoq = new Mock<FunctionContext>();
    contextMoq.Setup(X => X.RetryContext.RetryCount).Returns(1);
    contextMoq.Setup(X => X.RetryContext.MaxRetryCount).Returns(2);
    return contextMoq.Object;
}