]> git.somenet.org - pub/jan/dst18.git/blob - ass1-jpa/src/test/java/dst/ass1/jpa/tests/UniqueConstraintTester.java
Add template for assignment 3
[pub/jan/dst18.git] / ass1-jpa / src / test / java / dst / ass1 / jpa / tests / UniqueConstraintTester.java
1 package dst.ass1.jpa.tests;
2
3 import static org.junit.Assert.fail;
4
5 import java.util.function.Consumer;
6 import java.util.function.Supplier;
7
8 import javax.persistence.EntityManager;
9 import javax.persistence.EntityTransaction;
10 import javax.persistence.PersistenceException;
11
12 import org.hibernate.exception.ConstraintViolationException;
13
14 /**
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.
17  *
18  * @param <E> the entity type
19  */
20 public class UniqueConstraintTester<E> {
21
22     private Consumer<E> valueSetter;
23     private E e1;
24     private E e2;
25
26     public UniqueConstraintTester(E e1, E e2, Consumer<E> valueSetter) {
27         this.e1 = e1;
28         this.e2 = e2;
29         this.valueSetter = valueSetter;
30     }
31
32     public UniqueConstraintTester(Supplier<E> entityFactory, Consumer<E> valueSetter) {
33         this(entityFactory.get(), entityFactory.get(), valueSetter);
34     }
35
36     public void run(EntityManager em) {
37         EntityTransaction tx = em.getTransaction();
38         if (!tx.isActive()) {
39             tx.begin();
40         }
41
42         valueSetter.accept(e1);
43         em.persist(e1);
44         em.flush();
45
46         try {
47             valueSetter.accept(e2);
48             em.persist(e2);
49             em.flush();
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());
55             }
56         }
57     }
58 }