There exists an enum class that will cause problems downstream if it is changed without also making changes to the downstream project. Unfortunately, this is not easily identified by just searching for usages of the enum. We have had big warning comments in the code saying "Don't change this without also changing (downstream project)", but apparently that wasn't enough: Murphy's Law held firm. I need some other way of preventing other developers (or future me) from breaking things.
My current approach is to create a Unit test that will throw an error whenever the enum is changed. Changing the enum will therefore cause the build to fail which should get the attention of the developer. Included in the failure message will be instructions on how to safely update the enum. Unfortunately I can't see any way of writing this unit test short of copying the entire enum into the test class and then comparing every value from the test enum to the actual enum.
Is there a way that I can avoid duplicating the enum in the test class here? Is there a best practice that you recognize I should be following based on my description?
If all you want to verify is the enum member names and maybe their order, then you can create a static method on the enum type that computes a digested form of that information. Your unit test can then invoke a single method to test whether the enum matches expected form.
For example,
enum Test {
T1;
static int computeSignature() {
StringBuilder sb = new StringBuilder();
for (Test t : values) {
sb.append(t.name()).append(';');
}
return sb.toString().hashCode();
}
}
// ...
private final static int EXPECTED_ENUM_SIG = /* some number */;
@Test
public void testEnumSignature() {
assertEquals("enum Test has been unexpectedly changed", EXPECTED_ENUM_SIG,
Test.computeSignature());
}
If you decide you don't care about the enum order, then sort the names as part of the signature computation.
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