.NET 6下NUnit执行MVC控制器单元测试时依赖缺失问题
我有两个基于.NET 6的项目:
- 一个是包含MVC控制器的REST API项目
- 另一个是针对该API控制器编写的NUnit单元测试项目
在Visual Studio(搭配ReSharper)中执行单元测试一切正常,但通过Cake在CMD中执行时,抛出以下错误:
Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
----> Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
----> Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
我已尝试以下操作但未解决问题:
- 通过NuGet添加依赖,但对应版本仅支持.NET Framework,版本不匹配
- 修改测试项目的Sdk为
<Project Sdk="Microsoft.NET.Sdk.Web"> - 添加
Microsoft.Extensions.DependencyInjection.Abstractions(7.0.0版本)和Microsoft.AspNetCore.Mvc.Testing(6.0.13版本)的包引用
目前仅能通过手动下载缺失DLL添加引用作为临时方案,想了解是否有正规解决办法,比如NUnit相关配置设置。
解决方案
1. 统一目标框架版本
确保测试项目的.csproj中目标框架与API项目完全一致,均为net6.0:
<TargetFramework>net6.0</TargetFramework>
2. 配置项目引用的依赖复制
在测试项目的.csproj中,对API项目的引用添加PrivateAssets="all",确保构建时自动复制API项目的依赖到测试输出目录:
<ProjectReference Include="..\YourApiProject\YourApiProject.csproj"> <PrivateAssets>all</PrivateAssets> </ProjectReference>
3. 修正Cake脚本的测试执行逻辑
确保Cake脚本先完成构建和依赖还原,再执行测试,避免依赖未正确复制:
// 清理解决方案 DotNetClean("./YourSolution.sln"); // 还原所有依赖 DotNetRestore("./YourSolution.sln"); // 构建测试项目 DotNetBuild("./YourTestProject/YourTestProject.csproj", new DotNetBuildSettings { Configuration = "Release" }); // 执行测试,禁用NoBuild确保依赖已同步 DotNetTest("./YourTestProject/YourTestProject.csproj", new DotNetTestSettings { Configuration = "Release", NoBuild = false });
4. 统一ASP.NET Core包版本
将测试项目中所有ASP.NET Core相关包的版本统一为.NET 6.x,避免跨版本依赖冲突:
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.13" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.13" />
5. 配置NUnit的依赖加载规则
在测试项目根目录创建nunit.runsettings文件,启用影子复制和用户配置加载:
<RunSettings> <NUnit> <ShadowCopy>true</ShadowCopy> <LoadUserProfile>true</LoadUserProfile> </NUnit> </RunSettings>
然后在Cake脚本中指定该配置文件执行测试:
DotNetTest("./YourTestProject/YourTestProject.csproj", new DotNetTestSettings { Configuration = "Release", Settings = "./YourTestProject/nunit.runsettings" });
内容的提问来源于stack exchange,提问作者Kalyh

