I need to create a unique ID. It has to be 16 bytes long.
I came across to java.util.UUID and try to use UUID.randomUUID(). But how to make sure that the generated UUID to be 16 bytes long?
In my JUnit I tried to test using
Assert.assertTrue(stringUUID.getBytes().length() ==16)
Is this correct?
You do not need to unit test JDK classes (unless you are writing code for the JDK). java.util.UUID will create proper 16 byte unique ids. Focus on your testing efforts on your own code instead.
And for more readily understandable test case output (in case of failed assertions) it is better to use assertEquals:
assertEquals("UUID has expected length", 16, stringUUID.getBytes().length());
This will fail, however, because the string representation is longer than 16 bytes. What with hex-encoding and hyphens and all.
UUID.randomUUID() method generate a type-4 UUID. That is 36 byte long and have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.
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