codybchaplin
codybchaplin

Reputation: 169

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

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?

Upvotes: 5

Views: 696

Answers (2)

Tony Hughes
Tony Hughes

Reputation: 26

I have the same issue.

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

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

in .csproj file for maui app and

    <TargetFramework>net7.0</TargetFramework>

in unit test .csproj file.

Have tried shutting down VS, reloading projects. Not working.

Multiple build errors, including: 
Severity    Code    Description Project File    Line    Suppression State
Error   CS0246  The type or namespace name 'Xunit' could not be found (are you missing a using directive or an assembly reference?) 

Upvotes: 0

Bruno Guardia
Bruno Guardia

Reputation: 473

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>

Upvotes: 1

Related Questions