0

In short:

Is there an easy way to make a unit test to assert a combination of 2 Enum value combinations results in true while all other combinations results in false?

Detailed situation:

There is a method, taking two Enum values and returning bool. For this method, I want to write a Unit Test using xUnit and FluentAssertions.

public bool MethodUnderTest(State state, UserRole role)
{
    return state == State.Loaded
           && (role == UserRole.Admin
           || role == UserRole.PowerUser);
}

Until now, I made unit tests like this:

[Theory]
[InlineData(State.Loaded, UserRole.Admin, true)]
[InlineData(State.Loaded, UserRole.StandardUser, false)]
public void Test(State state, UserRole role, bool expectedResult)
{
    MethodUnderTest(state, role).Should().Be(expectedResult);
}

Now as there are more than 50 possible combinations of State and UserRole and a big bunch of methods to test, writing so many InlineData is rather annoying.

Possible solution:

I made some member generator methods using the MemberData attribute of xUnit. Method CreateCombinationscreates, depending on the bool parameter passed, all allowed or not allowed combinations of the Enum (I do not post this method as it is rather long). Of course I can do this generator more or less reusable. But having a generator method is not easy to understand for new developers introduced to the project in cause of the dynamic nature of this approach.

[Theory]
[MemberData(nameof(CreateCombinations), parameters: new object[] { new[] { State.Loaded }, new[] { UserRole.Admin, UserRole.PowerUser }, false })]

public static IEnumerable<object[]> CreateCombinations(State[] allowedStates, UserRole[] allowedRoles, bool isAllowedCombination)
{
    // depending on isAllowedCombination,
    // generating all allowed or not allowed combinations
    // using some foreach and yield return new object[] {state, role};
}
this.myself
  • 2,101
  • 2
  • 22
  • 36
  • The easy way would be to copy the code of method under test to the test and use it there to assert. However it defeats the purpose of the test. – Firo Mar 02 '23 at 08:48

0 Answers0