Created
December 8, 2016 15:08
-
-
Save compwron/cbcf6f918288dabab8825e6e62807b6b to your computer and use it in GitHub Desktop.
TimestampsTest osa being awesome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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