.NET Framework单元测试中System.Text.Json抛TypeInitializationException求解决
解决方案
1. 安装匹配版本的依赖包
System.Text.Json 9.0.1依赖System.Runtime.CompilerServices.Unsafe 4.7.1版本,给所有项目(重点是UnitTests1)安装该版本:
Install-Package System.Runtime.CompilerServices.Unsafe -Version 4.7.1
2. 修正单元测试项目的绑定重定向
在UnitTests1的App.config中添加完整的绑定重定向配置,确保版本匹配:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.7.1.0" newVersion="4.7.1.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
3. 强制复制所有依赖到测试输出目录
在UnitTests1的.csproj文件中添加以下配置,确保NuGet依赖文件被复制到测试运行目录:
<PropertyGroup> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup>
4. 清理重建解决方案
- 删除所有项目的
bin和obj文件夹 - 在Visual Studio中执行NuGet包还原操作
- 右键解决方案选择重建解决方案
备选方案(若上述步骤无效)
将ClassLibrary1中的System.Text.Json降级到8.0.4版本(该版本对.NET Framework 4.8的兼容性更稳定),再重复上述1-4步骤。
内容的提问来源于stack exchange,提问作者J.P.
相关产品推荐
相关产品推荐

