Developer Notes

Verify your functions can be instantiated with an integration test

Integration test : Function creation in .NET Core

In a previous post I talked about testing controller creation in an ASP.NET Core MVC or WebAPI type of application. Azure Functions don't use controllers though. They're a little more loosly defined by marking a method with an attribute. You can still use a similar test to verify that all functions in your project can be instantiated with dependency injection.

The integration test

This is an xUnit test and you can run this inside your CI/CD pipeline. The Functions method returns the types all classes that contain function methods. This works with both 'regular' Azure Functions and Azure Durable Functions and the activities that go with it.

In the Arrange phase of the test, the Function host is constructed and the type containing the function is added explicitly so we can easily verify the type can be instantiated.

By using GetRequiredService we force the container to return a proper error which includes any types missing form the dependency graph.

public class When_the_function_host_is_configured
{
[Theory]
[MemberData(nameof(Functions))]
public void It_should_be_able_to_instantiate_all_functions(Type functionType)
{
// Arrange
var startup = new MyFunctions.Startup();
var host = new HostBuilder()
.ConfigureWebJobs(cfg =>
{
startup.Configure(cfg);
cfg.Services.AddTransient(functionType);
})
.Build();
// Act
var function = host.Services.GetRequiredService(functionType);
// Assert
function.Should().NotBeNull();
}
public static IEnumerable<object[]> Functions
{
get
{
return typeof(Startup)
.Assembly
.GetTypes()
.SelectMany(t => t.GetMethods())
.Where(m => m.GetCustomAttributes(typeof(FunctionNameAttribute), false).Length > 0)
.Select(m => m.DeclaringType)
.Distinct()
.Select(t => new object[]
{
t
});
}
}
}

Further reading