Recently getting into adding unit tests to all my old projects to improve maintainability when I came across an interesting scenario regarding the suitability of adding assume()
statements under cases where failure of the assumed case is a remote possibility.
One such case is with the class UUID and it's randomUUID()
method. Given a scenario where a particular test depends on two randomly generated UUID to be distinct, is it excessive/unnecessary to add an assumption check for this case, e.g:
UUID firstUID = UUID.randomUUID();
UUID secondUID = UUID.randomUUID();
// Is this test excessive
assumeFalse(firstUID.equals(secondUID));
// Rest of test here
Whilst it can be seen from many places including here that UUID collisions are practically impossible, the javadoc for such a method does not claim it to be:
Static factory to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator.
The clause cryptographically strong pseudo random number generator
is assuring but no explicit statement is given to the uniqueness of generated UUIDs. This means that potentially future implementations of the randomUUID()
could change it's implementation such that collisions become more likely without breaking the declared contract of the method.
Whilst this case appears to be quite isolated, it does pop up from time to time especially when dealing with random number generation (also with prime number generation). From my perspective, adding a assumption clause does not contribute much to a performance hit so I left it in. But overall, are high probability (essentially practically impossible to fail) assumptions a good idea to add during unit tests? Or are they excessive? To take this further, are there guidelines to how likely a given assumption must fail before an actual assumption clause be written for them? I'm guessing assumeFalse(the world is ending)
would be considered excessive.
P.S: the actual code under specification uses a third party UUID generation system that is unknown to me but guarantees uniqueness. As this case is an extension to the original API I'm substituting their UUID generation with a dummy randomUUID()
such that the assumption is only probable for the test (100% for the actual code).
The alternative would be to write systems that guarantees the conditions (rather than just have a assumed high probability for them) though I find this excessive for small tests.