I have a method which builds an object and returns it.
The object as UUID as one of its fields. While building the object, random UUID is generated. Here is the code:
public MetaData getMetaData(String id) {
return MetaData.newBuilder().setId(id)
.setCorrelationId(UUID.randomUUID().toString())
.setCreatedAt(now(UTC).format(ISO_ZONED_DATE_TIME))
.build();
}
Here is my test:
@Test
public void shouldVerifyIfTheMetaDataIsBuild() {
MetaData metaData = handler.getMetaData("1234");
assertThat(metaData.getId(), is("1234"));
assertThat(metaData.getCorrelationId(), isNotNull());
}
I'm just verifying if the correlationId
is not null or not. Is there a better way to verify the UUID
?
The only way to verify the current production code is to, yes, check that CorrelationId is not null. You could also check that the layout of the expected string matches a valid UUID string.
Of course, when you want to a bit of better checking, then you simply have to replace UUID.randomUUID().toString()
with something that you can control.
For example you could create a UUIDGenerator
interface, with a default method that creates a random UUID, as shown in your code. But in your test setup, you instead provide an implementation of that interface that returns a specific UUID.
Then your test code could know which UUID should be used, and assertThat(actualUuid, is(expectedUuid))
.
I would change this line:
assertThat(metaData.getCorrelationId().toString(), isNotNull());
to the following:
assertThat(metaData.getCorrelationId(), isNotNull());
otherwise you would get a NullPointerException
if metaData.getCorrelationId()
returns null
instead of an assertion failure.
Additionally, you could test if metaData.getCorrelationId()
returns a string that represents a valid UUID, by trying to parse it:
try {
UUID.fromString(metaData.getCorrelationID());
} catch (IllegalArgumentException e) {
fail("Correlation ID is not a valid UUID: " + metaData.getCorrelationId());
}
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