Skip to content

Commit

Permalink
better ArgumentException serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp committed Sep 23, 2020
1 parent 1d582f6 commit 3f0d1ca
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<Project>
<PropertyGroup>
<NoWarn>CS1591;CS0649;xUnit1026</NoWarn>
<Version>6.20.0</Version>
<Version>6.21.0</Version>
<AssemblyVersion>1.0.0</AssemblyVersion>
<PackageTags>Json, Testing, Verify, Snapshot, Approvals</PackageTags>
<Description>Enables verification of complex models and documents.</Description>
Expand Down
5 changes: 5 additions & 0 deletions src/Verify.Tests/Tests.ThrowsArgumentException.verified.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
Type: 'ArgumentException',
Message: 'The Message',
ParamName: 'The parameter'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
Type: 'ArgumentNullException',
Message: 'The Message',
ParamName: 'The parameter'
}
22 changes: 22 additions & 0 deletions src/Verify.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,28 @@ static void MethodThatThrows()
throw new Exception("The Message");
}

[Fact]
public Task ThrowsArgumentException()
{
return Verifier.Throws(MethodThatThrowsArgumentException);
}

static void MethodThatThrowsArgumentException()
{
throw new ArgumentException("The Message", "The parameter");
}

[Fact]
public Task ThrowsInheritedArgumentException()
{
return Verifier.Throws(MethodThatThrowsArgumentNullException);
}

static void MethodThatThrowsArgumentNullException()
{
throw new ArgumentNullException("The parameter", "The Message");
}

[Fact]
public Task ThrowsAggregate()
{
Expand Down
10 changes: 10 additions & 0 deletions src/Verify/Serialization/CustomContractResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ string ResolveDictionaryKey(JsonDictionaryContract contract, string value)
return value;
}

FieldInfo exceptionMessageField = typeof(Exception).GetField("_message", BindingFlags.Instance | BindingFlags.NonPublic)!;

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization serialization)
{
var property = base.CreateProperty(member, serialization);
Expand All @@ -124,6 +126,14 @@ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerializ
return property;
}

if (member.Name == "Message")
{
if (member.DeclaringType == typeof(ArgumentException))
{
valueProvider = new ReflectionValueProvider(exceptionMessageField);
}
}

if (propertyType.IsException())
{
property.TypeNameHandling = TypeNameHandling.All;
Expand Down

0 comments on commit 3f0d1ca

Please sign in to comment.