Skip to content

Commit f0fac51

Browse files
committed
Add support to convert into to enum
1 parent 552d4f5 commit f0fac51

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Src/FluentAssertions/Equivalency/Steps/AutoConversionStep.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,18 @@ private static bool TryChangeType(object subject, Type expectationType, out obje
5656

5757
try
5858
{
59+
if (expectationType.IsEnum)
60+
{
61+
if (Enum.IsDefined(expectationType, subject))
62+
{
63+
subject = Enum.ToObject(expectationType, subject);
64+
}
65+
else
66+
{
67+
return false;
68+
}
69+
}
70+
5971
conversionResult = Convert.ChangeType(subject, expectationType, CultureInfo.InvariantCulture);
6072
return true;
6173
}

Tests/FluentAssertions.Equivalency.Specs/MemberConversionSpecs.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,32 @@ public void When_an_int_is_compared_equivalent_to_a_string_representing_the_numb
5151
act.Should().NotThrow();
5252
}
5353

54+
[Fact]
55+
public void Numbers_can_be_converted_to_enums()
56+
{
57+
// Arrange
58+
var expectation = new { Property = EnumFour.Three };
59+
var subject = new { Property = 3 };
60+
61+
// Act / Assert
62+
subject.Should().BeEquivalentTo(expectation, options => options.WithAutoConversion());
63+
}
64+
65+
[Fact]
66+
public void Numbers_that_are_out_of_range_cannot_be_converted_to_enums()
67+
{
68+
// Arrange
69+
var expectation = new { Property = EnumFour.Three };
70+
var subject = new { Property = 4 };
71+
72+
// Act
73+
Action act = () => subject.Should().BeEquivalentTo(expectation, options => options.WithAutoConversion());
74+
75+
// Assert
76+
act.Should().Throw<XunitException>()
77+
.WithMessage("*subject*Property*EnumFour*");
78+
}
79+
5480
[Fact]
5581
public void When_injecting_a_null_predicate_into_WithAutoConversionFor_it_should_throw()
5682
{

0 commit comments

Comments
 (0)