我在 Visual Studio 2022 17.12.4 中使用以下项目创建了一个(新)解决方案:
System.Text.Json
版本9.0.1Just.DoIt
调用 JsonSerializer.Serialize()Just.DoIt
Just.DoIt
Just.DoIt
这是
Just.DoIt
代码:
public static class Just
{
public static void DoIt()
{
var person = new Person { FirstName = "Jan", Age = 37, };
Console.WriteLine(person.ToString());
string json = JsonSerializer.Serialize(person);
Console.WriteLine(json);
var person2 = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine(person2.ToString());
}
}
public class Person
{
[JsonPropertyName("age")]
public int Age { get; set; }
[JsonPropertyName("firstname")]
public string FirstName { get; set; }
public override string ToString() { return $"{FirstName} ({Age})"; }
}
控制台应用程序和wpf应用程序工作正常,但单元测试在到达 JsonSerializer.Serialize() 时抛出异常:
Test method UnitTests1.JustDoItTest.TestMethod1 threw exception:
System.TypeInitializationException: The type initializer for 'System.Text.Json.JsonSerializer' threw an exception. ---> System.TypeInitializationException: The type initializer for 'PerTypeValues`1' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
我尝试了以下方法但没有解决问题:
System.Runtime.CompilerServices.Unsafe
6.1.0<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
还有:
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.1.0.0" newVersion="6.1.0.0" />
</dependentAssembly>
dotnet test
在 Visual Studio 之外运行测试。<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
添加到单元测试 .csproj 文件中。MSTest.TestFramework
和 MSTest.TestAdapter
。Microsoft.TestPlatform
。你知道我如何解决这个问题并且在单元测试项目中不出现异常吗?
我已经尝试解决这个问题两天了,现在我已经发布了问题,我找到了解决方案:$ stackoverflow.com/a/73557076/12924241 启发我将绑定重定向更改为正确的版本(6.0.1.0)。
这是带有绑定重定向的正确 App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<!--
This binding redirect is needed to make anything that involves calling System.Text.Json to work.
For some reason this is only needed in unit test projects.
-->
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.1.0" newVersion="6.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>