1

I'm trying to convert AssertFailedException to JToken and then to an Exception Object. The test code is pretty simple.

AssertFailedException testAssertException = new AssertFailedException(msg: "This is a test");
JToken assertJToken = JToken.FromObject(testAssertException);
assertJToken .ToObject<Exception>();

But looks like there are a few properties missing in AssertFailedException, such as ClassName, HelpURL, etc. (Not really missing but set to null). And it throws an error says

Member 'ClassName' was not found.
   at System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType)
   at System.Runtime.Serialization.SerializationInfo.GetString(String name)
   at System.Exception..ctor(SerializationInfo info, StreamingContext context)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType, JsonSerializer jsonSerializer)
   at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType)
   at Newtonsoft.Json.Linq.JToken.ToObject[T]()

What confuses me is there is no difference even if setting the NullValueHandling. The error still persists. The ask is, what's so special about AssertFailedException? Is there a way to make the test code work?

dbc
  • 104,963
  • 20
  • 228
  • 340
KevinC
  • 57
  • 5
  • 1
    Microsoft failed to add `[Serializable]` to [`AssertFailedException`](https://github.com/microsoft/testfx/blob/main/src/TestFramework/MSTest.Core/Exceptions/AssertFailedException.cs) so Json.NET does not serialize it as an `ISerializable`. `Exception` *does* have `[Serializable]` so the deserialization code does not use the same property names and serialization logic as the serialization code. – dbc Jul 05 '21 at 20:29
  • 1
    Use `PreferISerializableContractResolver` from [this answer](https://stackoverflow.com/a/50881884/3744182) to [Deserializing custom exceptions in Newtonsoft.Json](https://stackoverflow.com/q/50845255/3744182) when **serializing** to work around the problem. Demo fiddle here: https://dotnetfiddle.net/nhHcXT. – dbc Jul 05 '21 at 20:29

0 Answers0