二进制序列化 .NET Exception-derived class;使用 FluentAssertions 进行单元测试

Binary serialize a .NET Exception-derived class; unit testing with FluentAssertions

我有一个自定义异常,它在 ctor 中接受几个字符串,后跟通常的 Exception innerException 最后一个参数。异常 class 用 [Serializable] 修饰。此异常 class MyException 也继承自 MyBaseException 而后者又继承自 Exception.

我正在尝试对所有 ctor 参数进行单元测试,以确保所有 ctor 参数都正确地水合和脱水。这有效:

var error = new MyException("entityname1");
error.Should().BeBinarySerializable();

这不起作用:

var error = new MyException("entityname1",
    new InvalidOperationException("some error"));
error.Should().BeBinarySerializable();

它给出:

Expected MyException with message "Unable to sign-in “entityname1”."
 to be serializable, but serialization failed with:

Expected member InnerException
to be System.InvalidOperationException with message \"some error\"\n,
but found System.InvalidOperationException with message \"some error\"

抛出的错误没有可能提供问题思路的 innerException 信息。

有趣的是,这个有效:

var error = new MyException("entityname1", new MyOtherException("some error"));

知道为什么那个序列化失败 and/or 如何调试问题?

.NET 4.6.1 和 FluentAssertions 4.14.0

编辑:

鉴于@Evk 的发现,我手动尝试了 serializing/deserializing 一个带有 BinaryFormatter 的异常,它似乎工作正常:

var formatter = new BinaryFormatter();

var source = new Exception("some error");

byte[] buffer;
using (var stream = new MemoryStream())
{
    formatter.Serialize(stream, source);

    buffer = new byte[stream.Length];

    stream.Position = 0;
    stream.Read(buffer, 0, buffer.Length);
}

using (var stream = new MemoryStream(buffer))
{
    var ex = (Exception)formatter.Deserialize(stream);

    ex.ToString().Should().Be(source.ToString());
}

所以这可能是 FluentAssertions 中的错误。

这已在 FluentAssertions 中修复:

BeBinarySerializable fails with standard .NET exceptions, but not with custom exceptions