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))
.