OK I’ve created a basic abstract test gist here.
I’ll give a minimum reproducible example (in semi-pseudo semi-real code) below for future reference as well.
N.B. this requires the easy random library as a dependency and if you are using Java records you will currently need to initialise your EasyRandom()
instance with a workaround described here (this is not done in the example below). Once Java records become standard a newer version of easy random will support it out of the box (and you can define your API commands/events using records rather than relying on lombok annotations).
So given the following API:
class SomeAggregateCommandAPI {
@Value
public static class CreationCommand {
@TargerAggregateIdentifier UUID id;
String a;
}
@Value
public static class AggregateCreatedEvent {
UUID id;
String a;
}
/......
}
Suppose we want to test each of the commands/events are serializable/deserializable we can create our test class which extends the abstract class defined in the gist:
class SomeAggregateCommandAPISerializationTest extends AbstractAPISerializationTest {
@Override
public Serializer getSerializer() {
// Grab the serializer we use in our actual app.
return new SerializerConfig().messageSerializer();
}
/**
* Pass all the types we want to test the Serializer with.
*/
@Override
public List<Class<?>> getTypes() {
var classes = Arrays.asList(SomeAggregateCommandAPI.class.getClasses());
return new ArrayList<>(classes);
}
}
This will end up running the following test (see the gist above for full code):
@ParameterizedTest
@MethodSource("provideTypes")
void serializeDeserialize(Class<?> type) {
// Given: a random instance of the type and the serializer.
var instance = easyRandom.nextObject(type);
Serializer serializer = getSerializer();
// When: We attempt to serialize and deserialize it.
assertThatCode(() -> {
var serializedObject = serializer.serialize(instance, String.class);
serializer.deserialize(serializedObject);
})
// Then: it does not throw...
.doesNotThrowAnyException();
}
Hope this comes in handy for anyone who wants to be able to test serialization/deserialization of their API objects.
Regards,
vab2048