Last active
November 16, 2022 09:30
-
-
Save gdelafosse/eba934ce8e280e3e9ef33928e30f7362 to your computer and use it in GitHub Desktop.
Mockito ArgumentMatcher for JPA Entity
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
package my.matchers; | |
import com.mysema.codegen.StringUtils; | |
import org.apache.commons.lang3.reflect.FieldUtils; | |
import org.apache.commons.lang3.reflect.MethodUtils; | |
import org.hibernate.proxy.HibernateProxy; | |
import org.hibernate.proxy.LazyInitializer; | |
import org.mockito.ArgumentMatcher; | |
import org.springframework.util.CollectionUtils; | |
import javax.persistence.Id; | |
import java.lang.reflect.Field; | |
import java.util.List; | |
import static org.mockito.ArgumentMatchers.argThat; | |
public class EntityMatcher<T> implements ArgumentMatcher<T> { | |
private final T wanted; | |
public static <T> T entityEq(T value) { | |
return (T) argThat(new EntityMatcher(value)); | |
} | |
private EntityMatcher(T wanted) { | |
this.wanted = wanted; | |
} | |
@Override | |
public boolean matches(T actual) { | |
if (actual == null) { | |
return wanted == null; | |
} else if (getClass(actual).equals(getClass(wanted))) { | |
return getEntityId(actual).equals(getEntityId(wanted)); | |
} else { | |
return false; | |
} | |
} | |
private static Class getClass(Object pojo) { | |
if(pojo instanceof HibernateProxy) { | |
HibernateProxy hibernateProxy = (HibernateProxy) pojo; | |
LazyInitializer initializer = | |
hibernateProxy.getHibernateLazyInitializer(); | |
return initializer.getImplementation().getClass(); | |
} | |
return pojo.getClass(); | |
} | |
private static Object getEntityId(Object pojo) { | |
try { | |
if (pojo == null) | |
return null; | |
List<Field> fields = FieldUtils.getFieldsListWithAnnotation(pojo.getClass(), Id.class); | |
if (CollectionUtils.isEmpty(fields)) { | |
throw new RuntimeException("No Id in class " + pojo.getClass().getName()); | |
} | |
return MethodUtils.invokeMethod(pojo, String.format("get%s", StringUtils.capitalize(fields.get(0).getName()))); | |
} catch (Exception Object) { | |
throw new RuntimeException("Unable to get Id for class " + pojo.getClass().getName()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment