How to add an xUnit project to .NET 7 MAUI solution?

264 views Asked by At

I want to run unit tests on my view models, services, etc. on my .NET 7 MAUI app. I following this, but it's for .NET 6 so I found this which is for .NET 7 but it seems both use the same process. Anyway, I followed the steps after adding net7.0 to my target framework, all my nuget packages get removed and when trying to build, I get these errors:

error NETSDK1005: Assets file 'C:...project\obj\project.assets.json' doesn't have a target for 'net7.0'. Ensure that restore has run and that you have included 'net7.0' in the TargetFrameworks for your project.

error NU1201: Project is not compatible with net7.0 (.NETCoreApp,Version=v7.0). Project does not support any target frameworks.

main project:

<TargetFrameworks>net7.0;net7.0-android33.0</TargetFrameworks>
<OutputType Condition="'$(TargetFramework)' != 'net7.0'">Exe</OutputType>

xUnit project:

<TargetFramework>net7.0</TargetFramework>

It was suggested to unload/reload my project and restart Visual Studio which I tried but nothing has worked. How can I fix this?

1

There are 1 answers

0
Bruno Guardia On

The solution was found and presented by Gerald Versluis in his video

Unit Testing .NET MAUI Apps with xUnit

Summary:

  • On your MAUI project, add a core .Net target. My example is with .Net 8 but his is .Net 6, so this should work for any .Net core version. I am adding "net8.0" at the beginning:

Before

<TargetFrameworks>net8.0-android;net8.0-ios;net8.0-maccatalyst</TargetFrameworks>

After

<TargetFrameworks>net8.0;net8.0-android;net8.0-ios;net8.0-maccatalyst</TargetFrameworks>
  • Then we need, in the same project file, the output to be a Library in order to be consumed by the tests, but only when the target is the core framework.

Before

<OutputType>Exe</OutputType>

After

<OutputType Condition="'$(TargetFramework)' != 'net8.0'">Exe</OutputType>