Is There a Simple Way to Test If You Match One of a Set of Enumerations

How to test enum types?

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

How do I determine if an Enum value has one or more of the values it's being compared with?

You can do that by combining values with | and checking via &.

To check if the value contains either of the tags:

if ((myValue & (Tag.PrimaryNav | Tag.HomePage)) != 0) { ... }

The | combines the enums you're testing (bitwise) and the & tests via bitwise masking -- if the result isn't zero, it has at least one of them set.

If you want to test whether it has both of them set, you can do that as well:

Tag desiredValue = Tag.PrimaryNav | Tag.HomePage;
if ((myValue & desiredValue) == desiredValue) { ... }

Here we're masking off anything we don't care about, and testing that the resulting value equals what we do care about (we can't use != 0 like before because that would match either value and here we're interested in both).

Some links:

  • The & Operator
  • The | Operator

How to check if any flags of a flag combination are set?

If you want to know if letter has any of the letters in AB you must use the AND & operator. Something like:

if ((letter & Letters.AB) != 0)
{
// Some flag (A,B or both) is enabled
}
else
{
// None of them are enabled
}

How do I test if int value exists in Python Enum without using try/catch?

test for values

variant 1

note that an Enum has a member called _value2member_map_ (which is undocumented and may be changed/removed in future python versions):

print(Fruit._value2member_map_)
# {4: <Fruit.Apple: 4>, 5: <Fruit.Orange: 5>, 6: <Fruit.Pear: 6>}

you can test if a value is in your Enum against this map:

5 in Fruit._value2member_map_  # True
7 in Fruit._value2member_map_ # False

variant 2

if you do not want to rely on this feature this is an alternative:

values = [item.value for item in Fruit]  # [4, 5, 6]

or (probably better): use a set; the in operator will be more efficient:

values = set(item.value for item in Fruit)  # {4, 5, 6}

then test with

5 in values  # True
7 in values # False

add has_value to your class

you could then add this as a method to your class:

class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6

@classmethod
def has_value(cls, value):
return value in cls._value2member_map_

print(Fruit.has_value(5)) # True
print(Fruit.has_value(7)) # False

test for keys

if you want to test for the names (and not the values) i would use _member_names_:

'Apple' in Fruit._member_names_  # True
'Mango' in Fruit._member_names_ # False

Java: Check if enum contains a given string?

This should do it:

public static boolean contains(String test) {

for (Choice c : Choice.values()) {
if (c.name().equals(test)) {
return true;
}
}

return false;
}

This way means you do not have to worry about adding additional enum values later, they are all checked.

Edit: If the enum is very large you could stick the values in a HashSet:

public static HashSet<String> getEnums() {

HashSet<String> values = new HashSet<String>();

for (Choice c : Choice.values()) {
values.add(c.name());
}

return values;
}

Then you can just do: values.contains("your string") which returns true or false.

Check if value exists in enum in TypeScript

If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value) because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:

enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}

becomes:

{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}

So you just need to do:

if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}

If you get an error for: Property 'values' does not exist on type 'ObjectConstructor', then you are not targeting ES2017. You can either use this tsconfig.json config:

"compilerOptions": {
"lib": ["es2017"]
}

Or you can just do an any cast:

if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}

How to check if enum value is valid?

enum value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of enum X { A = 1, B = 3 }, the value of 2 is considered a valid enum value.

Consider 7.2/6 of standard:

For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax. It is possible to define an enumeration that has values not defined by any of its enumerators.

There is no retrospection in C++. One approach to take is to list enum values in an array additionally and write a wrapper that would do conversion and possibly throw an exception on failure.

See Similar Question about how to cast int to enum for further details.

Mocking Java enum to add a value to test fail case

If you can use Maven as your build system, you can use a much simpler approach. Just define the same enum with an additional constant in your test classpath.

Let's say you have your enum declared under the sources directory (src/main/java) like this:

package my.package;

public enum MyEnum {
A,
B
}

Now you declare the exact same enum in the test sources directory (src/test/java) like this:

package my.package

public enum MyEnum {
A,
B,
C
}

The tests see the testclass path with the "overloaded" enum and you can test your code with the "C" enum constant. You should see your IllegalArgumentException then.

Tested under windows with maven 3.5.2, AdoptOpenJDK 11.0.3 and IntelliJ IDEA 2019.3.1



Related Topics



Leave a reply



Submit