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 CreateCombinations
creates, 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};
}