Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 16 bytes uniqueId ( or UUID ) and test it

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?

like image 256
sridhar Avatar asked Dec 10 '25 13:12

sridhar


2 Answers

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.

like image 141
Thilo Avatar answered Dec 13 '25 04:12

Thilo


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.

like image 36
Abhishek bhutra Avatar answered Dec 13 '25 04:12

Abhishek bhutra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!