Adding xUnit Test to your .NET MAUI Project
In this article, you’ll learn how to add a unit test project with xUnit to your .NET MAUI app and how to resolve errors that you may encounter running your unit tests.
Let’s get started.
Create a new project with the same solution as your .NET MAUI app. This can be done by right-clicking on the Solution. Go to Add > New Project. From the Dialog box select “xUnit Test Project” then click Next.
Name your test project. Click Next.
Select your Framework. Click Create.
Note: The framework should match whatever is in your .NET MAUI project. As of this writing, the only option is .NET 6.0.
Once the project is created, it has a default class.
This test project should build and run. Whenever you run this test, this should pass as it doesn’t do anything yet. This can be done by right-clicking on the unit test project. Select “Run Tests”.
Now, we must add a reference to the .NET MAUI project that you need to test.
In your unit test project, go to Dependencies. Right-click, and select Add Project Reference.
Hit check and click OK.
Now, you can actually reference code from your .NET MAUI project and start testing.
You can immediately see an error whenever you run the test. But doesn’t mean that it’s not compatible and it’s not going to work.
So what’s the problem?
If you go to your .NET MAUI’s project file (also known as .csproj), you will see all these target frameworks:
<TargetFrameworks>net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
While in the unit test’s project file:
<TargetFramework>net6.0</TargetFramework>
The reason behind this error was the .NET MAUI project and unit test project target frameworks are not aligned.
How to fix this?
Let’s go ahead to your .NET MAUI project .csproj file and add a net6.0
target as well.
<TargetFrameworks>net6.0;net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
We also need to output the test as a DLL or a library. But the output type here is Exe.
<OutputType>Exe</OutputType>
The good thing here is that, the output type’s default value is library, which is what we need. To fix this, we need to have a condition to only do the output type as an Exe whenever the target framework is not net6.0
.
<OutputType Condition="'$(TargetFramework)' != 'net6.0'">Exe</OutputType>
Unload and reload your .NET MAUI project. You can also restart your Visual Studio just to make sure. With all these things in place, you will now be able to build and run your unit test project smoothly.
Well, that’s how you add a unit test project with xUnit to your .NET MAUI project. I hope you find it useful!
You can find the source code example on my GitHub.