How to use Xunit with Azure Functions in Visual Studio Code

testing one two testing...

How to use Xunit with Azure Functions in Visual Studio Code

While working on my Azure Resume Challenge project, I had to implement tests with Azure Functions .NET. Xunit seems to be the go to for these things.

1. Structure your project properly

Make sure your Functions and your tests live in peer folders. I am not 100% sure if this is necessary but when I tried otherwise, I was getting reference errors.

2. dotnet new xunit

In the directory where your tests will live, create a new xunit app.

dotnet new xunit

3. Add Microsoft.AspNetCore.Mvc to your Xunit app

In the direcotyr where your tests live, add the Microsoft.AspNetCore.Mvc package.

dotnet add package Microsoft.AspNetCore.Mvc

4. Reference your functions app from your Xunit app

You'll need to reference your functions app from where your tests live, it will look something like this, my functions live in a folder called api

dotnet add reference ../api/api.csproj

This should create an item group in your test csproj, similar to:

    <ProjectReference Include="..\api\api.csproj" />

5. Test the setup

Finally run dotnet test to make sure you get no errors, you're now ready to add the supporting files and your first test. Checkout this Microsoft documentation page, it has an example HTTP and Timer trigger test you can implement.

Subscribe to madebygps

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.