Is there any clean way of testing that a given String matches an enum name?
Right now I get
Expected: is <SUNDAY>
Actual: SUNDAY
I want to avoid having to add .name()
to each check
assertThat("SUNDAY", is(SUNDAY.name()))
Something as
assertThat("SUNDAY", isEnum(SUNDAY))
I'm not asking how to write my own Matcher
, I'm asking if there is already something built, which I can't seem to find.
Option 1
You can use Enum.valueOf(DAYS.class, "Sunday")
. I just named your enum DAYS
because I don't know its name. This is what Enum.valueOf
does:
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
In other words, in case there exists such enum value, you will get an enum instance, otherwise you will get an exception. So you can just assert the result and check whether you get a value or an exception gets thrown.
Option 2
You can create a HashSet
as follows:
HashSet<String> set = new HashSet<>();
for (final DAYS day : EnumSet.allOf(DAYS.class)) {
set.add(day.name());
}
And just check whether the set contains
the specific day:
assertTrue(set.contains("SUNDAY")); //Hope I'm using the assertion syntax right. Haven't used this framework before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With