已引用System.Xml.XDocument仍报错?C#单元测试FluentAssertions问题
解决FluentAssertions单元测试中XDocument引用错误问题
问题场景
在使用FluentAssertions编写C#单元测试时,执行以下断言语句:
internalModel.GetSections().First().GetTextAreas().First().Content.Should().NotBe("someContent","Some reason");
抛出错误:
The type 'XDocument' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml.XDocument, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
已确认信息:
- 项目依赖中已添加System.Xml.XDocument引用
- 测试文件包含必要的
using语句 - 单独执行
internalModel.GetSections().First().GetTextAreas().First().Content可得到正确结果 - 同一测试类中其他用例能正常使用FluentAssertions的
Should()方法
可能原因
- 版本不匹配:FluentAssertions依赖特定版本(4.1.1.0)的System.Xml.XDocument,但项目引用的版本与之不一致,导致程序集绑定失败。
- 测试项目未显式引用:主项目虽已引用该程序集,但测试项目未显式添加对应版本的引用,依赖未正确传递。
- NuGet包冲突:项目中其他NuGet包引入了不同版本的System.Xml.XDocument,引发版本冲突,编译器无法定位正确的程序集。
- 断言类型触发依赖:
Content属性的类型为XDocument(或内部嵌套XDocument),FluentAssertions在处理该类型的断言逻辑时,需要加载指定版本的程序集,但当前环境未满足。
解决办法
显式添加指定版本引用
打开测试项目的csproj文件,添加或修改对应引用节点:
若为.NET Core/.NET 5+项目:<PackageReference Include="System.Xml.XDocument" Version="4.1.1.0" />若为.NET Framework项目:
<Reference Include="System.Xml.XDocument, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />解决版本冲突
- 打开NuGet包管理器,查看测试项目中System.Xml.XDocument的所有引用,统一版本为4.1.1.0
- 若为.NET Framework项目,可添加程序集绑定重定向到csproj的
<runtime>节点:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Xml.XDocument" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" /> </dependentAssembly> </assemblyBinding> </runtime>绕开XDocument类型断言
若Content为XDocument类型,可先转换为字符串再执行断言,避免FluentAssertions直接处理该类型:internalModel.GetSections().First().GetTextAreas().First().Content.ToString() .Should().NotBe("someContent", "Some reason");清理重建解决方案
删除项目的bin、obj目录,执行dotnet nuget locals all --clear清理NuGet缓存,然后重新构建解决方案,确保依赖正确加载。
内容的提问来源于stack exchange,提问作者Maya
相关产品推荐
相关产品推荐

