1 package dst.ass1.jpa.tests;
3 import static org.junit.Assert.fail;
5 import java.util.function.Consumer;
6 import java.util.function.Supplier;
8 import javax.persistence.EntityManager;
9 import javax.persistence.EntityTransaction;
10 import javax.persistence.PersistenceException;
12 import org.hibernate.exception.ConstraintViolationException;
15 * Tests a unique constraint by creating two instances of an entity, calling the same value setter on each entity,
16 * and finally trying to persist them.
18 * @param <E> the entity type
20 public class UniqueConstraintTester<E> {
22 private Consumer<E> valueSetter;
26 public UniqueConstraintTester(E e1, E e2, Consumer<E> valueSetter) {
29 this.valueSetter = valueSetter;
32 public UniqueConstraintTester(Supplier<E> entityFactory, Consumer<E> valueSetter) {
33 this(entityFactory.get(), entityFactory.get(), valueSetter);
36 public void run(EntityManager em) {
37 EntityTransaction tx = em.getTransaction();
42 valueSetter.accept(e1);
47 valueSetter.accept(e2);
50 fail("Missing unique constraint in " + e2.getClass());
51 } catch (PersistenceException e) {
52 Throwable cause = e.getCause();
53 if (!(cause instanceof ConstraintViolationException)) {
54 fail("Missing unique constraint in " + e2.getClass());