I have a custom exception that takes in a couple strings in the ctor followed by the usual Exception innerException
last parameter. The exception class is decorated with [Serializable]
. This exception class MyException
also inherits from MyBaseException
which in turn inherits from Exception
.
I'm trying to unit test that all the ctor parameters hydrate and dehydrate properly. This works:
var error = new MyException("entityname1");
error.Should().BeBinarySerializable();
This does not work:
var error = new MyException("entityname1",
new InvalidOperationException("some error"));
error.Should().BeBinarySerializable();
It gives:
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\"
The error being thrown has no innerException information that might give an idea of the problem.
Interestingly, this works:
var error = new MyException("entityname1", new MyOtherException("some error"));
Any idea why that one serialization fails and/or how to debug the problem?
.NET 4.6.1 and FluentAssertions 4.14.0
EDIT:
Given what @Evk discovered, I tried manually serializing/deserializing an Exception with the BinaryFormatter
and it seems to work fine:
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());
}
So maybe this is a bug in FluentAssertions.
This has been fixed in FluentAssertions:
BeBinarySerializable fails with standard .NET exceptions, but not with custom exceptions