From d54042fee985138f4a55543a22170efd934d7829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 19 Feb 2025 12:50:45 +0100 Subject: [PATCH] Add SerializationBinder to formatter we use in tests --- ...aryFormatterExceptionSerializationTests.cs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/test/UnitTests/TestFramework.UnitTests/Exceptions/BinaryFormatterExceptionSerializationTests.cs b/test/UnitTests/TestFramework.UnitTests/Exceptions/BinaryFormatterExceptionSerializationTests.cs index 7c3a083458..3c33da1fad 100644 --- a/test/UnitTests/TestFramework.UnitTests/Exceptions/BinaryFormatterExceptionSerializationTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Exceptions/BinaryFormatterExceptionSerializationTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -32,13 +33,30 @@ private void VerifySerialization(Action actionThatThrows) // Ensure the thrown exception can be serialized and deserialized by binary formatter to keep compatibility with it, // even though it is obsoleted and removed in .NET. var mem = new MemoryStream(); - new BinaryFormatter().Serialize(mem, ex); + var formatter = new BinaryFormatter + { + Binder = new FormatterBinder(), + }; + formatter.Serialize(mem, ex); mem.Position = 0; - new BinaryFormatter().Deserialize(mem); + string str = Encoding.UTF8.GetString(mem.GetBuffer(), 0, (int)mem.Length); + Assert.IsNotNull(str); + var deserializedException = (Exception)formatter.Deserialize(mem); + + Assert.AreEqual(ex.Message, deserializedException.Message); return; } throw new InvalidOperationException($"The provided '{nameof(actionThatThrows)}' did not throw any exception."); } + + /// + /// This is for compliance, usage of BinaryFormatter without binder is not allowed. + /// + private class FormatterBinder : SerializationBinder + { + public override Type BindToType(string assemblyName, string typeName) + => null!; + } }