Home > Software design >  How to UnitTest a custom Exeption with SerializationInfo correctly?
How to UnitTest a custom Exeption with SerializationInfo correctly?

Time:10-07

I have my own Exception and because of SonarQube I implemented all 4 base constructures of System.Exception:

[Serializable]
public class DatabaseVersionNotReadableException : Exception
{
    private static readonly string Text = "Database Version not found or not readable: {0}";
    
    public DatabaseVersionNotReadableException()
    {
        
    }
    
    public DatabaseVersionNotReadableException(string version)
        : base(String.Format(Text, version))
    {

    }
    
    public DatabaseVersionNotReadableException(string version, Exception exception) : base(String.Format(Text, version), exception)
    {
        
    }
    
    protected DatabaseVersionNotReadableException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
        
    }
}

To unit test the first 3 const was very easy, but I have no idea how to setup a SerializationInfo and / or StreamingContext correctly to even get a simple test together. I tried find it out with google, but there seem to be no information about it.

How to unit test it?

CodePudding user response:

That API is used by BinaryFormatter for custom deserialization; so: serialize and deserialize your exception with BinaryFormatter.

Except, don't; BinaryFormatter is obsolete, deprecated and dangerous. IMO, unless you absolutely need that capability (for example, you're using "remoting" in .NET Framework and anticipate this exception going over the remoted boundary): just don't include it, and don't add [Serializable].

  • Related