Skip to content

Instantly share code, notes, and snippets.

@compwron
Created December 8, 2016 15:08
Show Gist options
  • Save compwron/cbcf6f918288dabab8825e6e62807b6b to your computer and use it in GitHub Desktop.
Save compwron/cbcf6f918288dabab8825e6e62807b6b to your computer and use it in GitHub Desktop.
TimestampsTest osa being awesome
import org.junit.Test;
import org.reflections.Reflections;
import javax.persistence.Entity;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class TimestampsTest {
@Test
public void allRepositoriesHaveCreatedAndUpdatedTimestamps() {
Reflections reflections = new Reflections("com.myapp");
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Entity.class);
validateMethodsExists(classes);
validateAnnotationExists(classes);
}
private void validateAnnotationExists(Set<Class<?>> classes) {
for (Class<?> aClass : classes) {
List<Method> collect = Arrays.stream(aClass.getDeclaredMethods())
.filter(method -> Arrays.stream(method.getAnnotations())
.filter(annotation ->
annotation.toString().equalsIgnoreCase("@javax.persistence.PrePersist()") ||
annotation.toString().equalsIgnoreCase("@javax.persistence.PreUpdate()"))
.count() > 0)
.collect(Collectors.toList());
String errorMessage = generateErrorMessage(aClass);
assertThat(errorMessage, collect.size(), is(2));
}
}
private void validateMethodsExists(Set<Class<?>> classes) {
for (Class<?> clazz : classes) {
List<Method> collect = Arrays.stream(clazz.getDeclaredMethods())
.filter(method -> method.getName().equals("getCreatedAt") || method.getName().equals("getUpdatedAt"))
.collect(Collectors.toList());
String errorMessage = generateErrorMessage(clazz);
assertThat(errorMessage, collect.size(), is(2));
}
}
private String generateErrorMessage(Class<?> aClass) {
StringBuilder sb = new StringBuilder();
String tab = "\n\t";
sb.append("\n\n")
.append("Every @Entity class must have a createdAt and UpdatedAt timestamp for auditing purposes")
.append("and must have annotations:")
.append("\n")
.append(tab + "1. @javax.persistence.PrePersist()")
.append(tab + "2. @javax.persistence.PreUpdate()")
.append("\n\n")
.append("Class: ").append(aClass.getName()).append(" does not comply aforementioned rule")
.append("\n\n");
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment