Skip to content

Instantly share code, notes, and snippets.

@dpolivaev
Last active January 28, 2020 12:57
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 dpolivaev/5458f51b51770a880b34be045a1a35a2 to your computer and use it in GitHub Desktop.
Save dpolivaev/5458f51b51770a880b34be045a1a35a2 to your computer and use it in GitHub Desktop.
import static org.junit.Assert.fail;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.EmbeddedId;
import javax.persistence.IdClass;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.EqualsVerifierApi;
import nl.jqno.equalsverifier.EqualsVerifierReport;
import nl.jqno.equalsverifier.Warning;
/**
* <pre>{@code
public class EqualsTest {
@Test
public void verifyHibernateEquals() throws Exception {
HibernateIdEqualsVerifier.verify(Application.class.getPackage().getName());
}
}
* }</pre>
*/
public class HibernateIdEqualsVerifier {
public static void verify(String basePackage) {
Reflections reflections = new Reflections(basePackage, //
new SubTypesScanner(), //
new TypeAnnotationsScanner(), //
new FieldAnnotationsScanner());
Set<Class<?>> checkedClasses = new HashSet<>();
reflections.getTypesAnnotatedWith(IdClass.class).stream()//
.map(c -> c.getAnnotation(IdClass.class))//
.map(IdClass::value)//
.forEach(checkedClasses::add);
reflections.getFieldsAnnotatedWith(EmbeddedId.class).stream()//
.map(f -> f.getType())//
.forEach(checkedClasses::add);
String report = checkedClasses.stream()//
.map(HibernateIdEqualsVerifier::configureVerifier)
.map(EqualsVerifierApi::report)//
.filter(r -> ! r.isSuccessful())//
.map(EqualsVerifierReport::getMessage)//
.collect(Collectors.joining("\n"));
if(! report.isEmpty())
fail(report);
}
private static <T> EqualsVerifierApi<T> configureVerifier(Class<T> checkedClass){
return EqualsVerifier.forClass(checkedClass).usingGetClass()//
.suppress(Warning.NONFINAL_FIELDS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment