hardfork
hardfork

Reputation: 3251

How to unit test the (de)serialization of a custom exception without BinaryFormatter?

There are a lot of StackOverflow answers explaining how to write a unit test for a custom exception class.

But all of them use the class BinaryFormatter to serialize and deserialize. Problem: It is suggested, not to use it anymore.

But how to do it then?

This is the code so far (with BinarFormatter):

        [TestMethod]
        public void test()
        {
            // Arrange
            const string TestMessage = "testMessage";
            var exception = new AbcException(TestMessage);
            using var stream = new MemoryStream();
            var formatter = new BinaryFormatter();

            // Act
            formatter.Serialize(stream, exception);
            stream.Position = 0; // Reset stream position

            var deserializedException = (AbcException)formatter.Deserialize(stream);

            // Assert
            Assert.AreEqual(TestMessage, deserializedException.Message);
        }

Upvotes: 1

Views: 713

Answers (1)

JonasH
JonasH

Reputation: 36341

I suspect the recommendations originate with .Net remoting, i.e. if a remote call produces an exception it needs to be serialized to transfer to the client.

.Net remoting is fairly rare in modern development that usually use REST or some other more modern protocol for client-server communication, and these usually have some other way to report errors, like http status codes.

So in practice I see little need to write unit tests to test serialization of exceptions unless you actually use .Net remoting or any other binaryFormatter-based technology. And if you do, you might think about migrating to newer technologies.

So my recommendations would be to just not write any such tests. And in general, if you don't know why you are writing a unit test, don't. Or at least, try to find out why such recommendations exist before following them.

Upvotes: 1

Related Questions