1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| @RunWith(Arquillian.class)
public class TestPU {
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap
.create(JavaArchive.class)
.addPackage(Contact.class.getPackage())
.addAsResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsResource("test-persistence.xml",
"META-INF/persistence.xml")
.addAsResource("test-ds.xml");
}
private static Map<String, String> datas = new HashMap<String, String>();
@PersistenceContext
EntityManager em;
@Inject
UserTransaction utx;
@Before
public void preparePersistenceTest() throws Exception {
if(em==null){
System.out.println("Entity Manager non injecté!");
}
datas.put("François", "Delalleau");
datas.put("Yann", "Leroy");
clearData();
insertData();
startTransaction();
}
public void clearData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Dumping old records...");
em.createQuery("delete from Game").executeUpdate();
utx.commit();
}
public void insertData() throws Exception {
utx.begin();
em.joinTransaction();
System.out.println("Inserting records...");
for (String prenom : datas.keySet()) {
Contact contact = new Contact("Monsieur", prenom, datas.get(prenom));
em.persist(contact);
}
utx.commit();
// clear the persistence context (first-level cache)
em.clear();
}
public void startTransaction() throws Exception {
utx.begin();
em.joinTransaction();
}
@SuppressWarnings("unchecked")
@Test
public void retrouverLesDeux(){
String query = "Select c from Contact c order by c.id";
List<Contact> result = em.createQuery(query).getResultList();
assertContainsLesDeux(result);
}
public void assertContainsLesDeux(List<Contact> result) {
Assert.assertEquals(datas.size(), result);
Map<String, String> resultContent = new HashMap<String, String>();
for(Contact contact : result){
resultContent.put(contact.getPrenom(), contact.getNom());
}
Assert.assertEquals(resultContent, datas);
}
@After
public void commitTransaction() throws Exception {
utx.commit();
}
} |
Partager