Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idea: int.ShouldBe(enum) methods #876

Open
benmccallum opened this issue Feb 3, 2023 · 0 comments
Open

Idea: int.ShouldBe(enum) methods #876

benmccallum opened this issue Feb 3, 2023 · 0 comments

Comments

@benmccallum
Copy link

benmccallum commented Feb 3, 2023

Was playing around with this idea today. I imagine it's a pretty common pattern to have enums for common things you might only have an int value for on say a db entity. This makes debugging the issue much easier as you get the enum member name on the end of the custom message.

It may be possible to have this wrap an enum.ShouldBe(enum) method too, but haven't played around with that yet. It might offer a better output upfront.

This could also be extended to byte, short, etc I guess.

Usage

enum Status { Active, Inactive }

var statusId = sut.GetStatus(foo);
statusId.ShouldBe(StatusEnum.Active, "Has x, should be active");

Output

Message: 
Shouldly.ShouldAssertException : actual
    should be
0
    but was
1

Additional Info:
    Has x, should be active (Expected: Active Actual: Inactive).

Impl

public static class Exts
    {
        public static void ShouldBe<T>(
            [NotNullIfNotNull("expected")] this int actual,
            [NotNullIfNotNull("actual")] T expectedAsEnum,
            string? customMessage = null)
            where T : struct, Enum
        {
            var actualAsEnum = Enum.Parse<T>(actual.ToString());
            var expected = Convert.ToInt32(expectedAsEnum);
            customMessage += $" (Expected: {expectedAsEnum} Actual: {actualAsEnum}).";

            actual.ShouldBe(expected, customMessage);
        }

        public static void ShouldBe<T>(
            [NotNullIfNotNull("expected")] this int? actual,
            [NotNullIfNotNull("actual")] T? expectedAsEnum,
            string? customMessage = null)
            where T : struct, Enum
        {
            var actualAsEnum = actual is null ? (T?)null : Enum.Parse<T>(actual.ToString()!);
            var expected = expectedAsEnum is null ? (int?)null : Convert.ToInt32(expectedAsEnum);
            customMessage += $" (" +
                $"Expected: {expectedAsEnum?.ToString() ?? "null"} " +
                $"Actual: {actualAsEnum?.ToString() ?? "null"}).";

            actual.ShouldBe(expected, customMessage);
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant