Skip to content

Commit

Permalink
Merge pull request fluentassertions#2261 from jnyrup/auto_conversion
Browse files Browse the repository at this point in the history
Fix auto conversion to enums
  • Loading branch information
jnyrup authored Aug 16, 2023
2 parents 292b9dd + 174bb4c commit 818e7dc
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
4 changes: 2 additions & 2 deletions Src/FluentAssertions/Equivalency/Steps/AutoConversionStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ private static bool TryChangeType(object subject, Type expectationType, out obje
{
if (expectationType.IsEnum)
{
if (Enum.IsDefined(expectationType, subject))
if (subject is sbyte or byte or short or ushort or int or uint or long or ulong)
{
conversionResult = Enum.ToObject(expectationType, subject);
return true;
return Enum.IsDefined(expectationType, conversionResult);
}

return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,36 @@ public void Numbers_can_be_converted_to_enums()
{
// Arrange
var expectation = new { Property = EnumFour.Three };
var subject = new { Property = 3 };
var subject = new { Property = 3UL };

// Act / Assert
subject.Should().BeEquivalentTo(expectation, options => options.WithAutoConversion());
}

[Fact]
public void Enums_are_not_converted_to_enums_of_different_type()
{
// Arrange
var expectation = new { Property = EnumTwo.Two };
var subject = new { Property = EnumThree.Two };

// Act / Assert
subject.Should().BeEquivalentTo(expectation, options => options.WithAutoConversion());
}

[Fact]
public void Strings_are_not_converted_to_enums()
{
// Arrange
var expectation = new { Property = EnumTwo.Two };
var subject = new { Property = "Two" };

// Act / Assert
var act = () => subject.Should().BeEquivalentTo(expectation, options => options.WithAutoConversion());

act.Should().Throw<XunitException>();
}

[Fact]
public void Numbers_that_are_out_of_range_cannot_be_converted_to_enums()
{
Expand Down
2 changes: 2 additions & 0 deletions docs/_pages/releases.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ sidebar:
### Fixes
* `because` and `becauseArgs` were not included in the error message when collections of enums were not equivalent - [#2214](https://github.com/fluentassertions/fluentassertions/pull/2214)
* Improve caller identification for tests written in Visual Basic - [#2254](https://github.com/fluentassertions/fluentassertions/pull/2254)
* Improved auto conversion to enums for objects of different integral type - [#2261](https://github.com/fluentassertions/fluentassertions/pull/2261)
* Fixed exceptions when trying to auto convert strings or enums of different type to enums- [#2261](https://github.com/fluentassertions/fluentassertions/pull/2261)

## 6.11.0

Expand Down

0 comments on commit 818e7dc

Please sign in to comment.