.NET MAUI类库无法用XUnit单元测试的问题求助
问题根源
你的MAUI类库项目在Windows平台下的目标框架配置存在覆盖问题:
- 初始的
<TargetFrameworks>包含通用的net7.0框架,这是XUnit测试项目(目标为.NETCoreApp,Version=v7.0)能够引用的基础 - 但Windows平台的条件配置
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">net7.0-windows10.0.19041.0</TargetFrameworks>是直接替换了原有的目标框架列表,导致在Windows环境下,类库仅编译net7.0-windows10.0.19041.0这一个特定框架,丢失了通用的net7.0目标 - XUnit测试项目无法引用仅包含Windows特定框架的类库,因此抛出框架不兼容的错误
解决方案
修改Windows平台的目标框架配置,改为追加而非替换原有框架列表,保留通用的net7.0目标:
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net7.0-windows10.0.19041.0</TargetFrameworks>
修改后的完整PropertyGroup部分如下:
<PropertyGroup> <TargetFrameworks>net7.0-android;net7.0-ios;net7.0-maccatalyst;net7.0</TargetFrameworks> <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net7.0-windows10.0.19041.0</TargetFrameworks> <UseMaui>true</UseMaui> <SingleProject>true</SingleProject> <ImplicitUsings>enable</ImplicitUsings> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">14.2</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">14.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion> <TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion> <Platforms>AnyCPU;x86;x64;ARM64;ARM32</Platforms> </PropertyGroup>
效果说明
- 配置修改后,Windows环境下类库会同时编译通用
net7.0和Windows特定net7.0-windows10.0.19041.0框架,XUnit测试项目可以正常引用通用框架版本 - MAUI项目依然能使用Windows特定框架运行Windows端应用,不会丢失原有功能
内容的提问来源于stack exchange,提问作者kerry
相关产品推荐
相关产品推荐

