Skip to content

Instantly share code, notes, and snippets.

@vab2048
Created January 7, 2021 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vab2048/467d74d3b7db9de30ba0a63d39a3a56f to your computer and use it in GitHub Desktop.
Save vab2048/467d74d3b7db9de30ba0a63d39a3a56f to your computer and use it in GitHub Desktop.
Class for testing if type is serializable and deserializable with a given Axon serializer.
import org.axonframework.serialization.Serializer;
import org.jeasy.random.EasyRandom;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThatCode;
/**
* Class containing generic test to verify the given types are serializable and deserializable.
*
* We use the Lifecycle.PER_CLASS option so that a non-static method source can be used for our
* parameterized tests.
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class AbstractAPISerializationTest {
/**
* Easy random instance we will use to generate random instances of the classes
* we want to test are serializable/deserializable.
*/
public static final EasyRandom easyRandom = new EasyRandom();
/**
* Get the serializer under test.
*/
public abstract Serializer getSerializer();
/**
* Retrieve the class types of those classes we want to test are serializable/deserializable.
* The concrete class will implement this as it sees fit.
*/
public abstract List<Class<?>> getTypes();
/**
* Wraps the result of getTypes() into a form which can be provided to a test as a method source.
*/
private Stream<Arguments> provideTypes() {
return getTypes().stream().map(Arguments::of);
}
@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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment