You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI ViewModel XUnit测试报错:找不到Microsoft.Maui.Controls

非预览版.NET MAUI ViewModel单元测试解决方案

方案一:用Mock隔离MAUI依赖

这是最推荐的做法,从根源上避免测试项目依赖MAUI类库:

  • 把VM_AppSettings中用到的MAUI Essentials/Controls功能,抽象成独立接口。比如用到Preferences的话,定义:
    public interface IPreferencesService
    {
        string Get(string key, string defaultValue);
        void Set(string key, string value);
    }
    
  • 在MAUI项目里写这个接口的实现,内部调用真正的Microsoft.Maui.Essentials.Preferences。
  • 修改VM_AppSettings的构造函数,注入IPreferencesService而不是直接引用MAUI组件。
  • 测试时用Moq这类框架创建IPreferencesService的模拟实例,传给VM_AppSettings,完全不需要引用MAUI的类库。

方案二:手动配置测试项目的MAUI程序集引用

如果必须保留对MAUI类库的依赖,可以调整测试项目的csproj:

  1. 在PropertyGroup里添加:
    <UseMaui>true</UseMaui>
    <UseMauiEssentials>true</UseMauiEssentials>
    <OutputType>Library</OutputType>
    
  2. 添加匹配版本的MAUI包引用:
    <PackageReference Include="Microsoft.Maui.Controls" Version="7.0.92" />
    <PackageReference Include="Microsoft.Maui.Controls.Compatibility" Version="7.0.92" />
    
    注意版本号要和你的MAUI主项目一致,比如.NET7用7.0.xx系列。
  3. 如果测试项目用的是net7.0(而非特定平台TargetFramework),手动指定程序集路径:
    <ItemGroup>
      <Reference Include="Microsoft.Maui.Essentials">
        <HintPath>..\YourMauiProjectName\bin\Debug\net7.0\Microsoft.Maui.Essentials.dll</HintPath>
      </Reference>
      <Reference Include="Microsoft.Maui.Controls">
        <HintPath>..\YourMauiProjectName\bin\Debug\net7.0\Microsoft.Maui.Controls.dll</HintPath>
      </Reference>
    </ItemGroup>
    
    把YourMauiProjectName换成你的MAUI项目名称,确保路径正确。

方案三:使用MAUI测试框架初始化环境

针对.NET7,借助Microsoft.Maui.Testing包来模拟MAUI运行环境:

  1. 安装和MAUI版本匹配的Microsoft.Maui.Testing NuGet包。
  2. 在测试类里初始化MAUI的DI容器:
    [Collection(nameof(MauiTestCollection))]
    public class NearbyPlacesVmTests
    {
        private readonly IServiceProvider _services;
    
        public NearbyPlacesVmTests()
        {
            var builder = MauiApp.CreateBuilder();
            // 注册你的ViewModel和依赖,和MauiProgram.cs里的方式一致
            builder.Services.AddSingleton<VM_AppSettings>();
            builder.Services.AddSingleton<VM_NearbyPlaces>();
            // 要是需要替换MAUI服务,直接在这里覆盖就行
            var app = builder.Build();
            _services = app.Services;
        }
    
        [Fact]
        public void NearbyPlacesVm_Should_Initialize_Properly()
        {
            var vm = _services.GetRequiredService<VM_NearbyPlaces>();
            // 写你的测试断言
        }
    }
    
    这种方式会在测试中模拟MAUI的运行环境,解决程序集找不到的问题。

内容的提问来源于stack exchange,提问作者George M Ceaser Jr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 16:48:16