package javaeems.chapter1.model;

import static org.junit.Assert.*;

import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ModelEJBTest {

	private ModelEJB ejb;
	
	private EntityManagerFactory emf;
	
	@Before
	public void setUp() {
		ejb = new ModelEJB();
		emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
		ejb.em = emf.createEntityManager();
	}
	
	@After
	public void tearDown() {
		if (ejb.em != null) {
			ejb.em.close();
		}
		if (emf != null) {
			emf.close();
		}
	}
	
	@Test(expected=MessageException.class)
	public void testNothingInDB() throws MessageException {
		ejb.getStoredMessage();
	}

	@Test
	public void testSetAndGet() throws MessageException {
		EntityTransaction tx = ejb.em.getTransaction();
		try {
			tx.begin();
			ejb.putUserMessage("hello");
			ejb.putUserMessage("some statistically improbable phrase");
		} finally {
			tx.commit();
		}
		long numEntries = (long) ejb.em.createQuery("select count(m) from Message m").getSingleResult();
		assertEquals(1, numEntries);
		String message = ejb.getStoredMessage();
		assertTrue(message.contains("some statistically improbable phrase"));
	}
}

@@ -573,24 +573,200 @@
  != null) %7B%0A
+%09%09%09EntityTransaction tx = ejb.em.getTransaction();%0A%09%09%09try %7B%0A%09%09%09%09tx.begin();%0A%09%09%09%09ejb.em.createQuery(%22delete from Message%22).executeUpdate();%0A%09%09%09%7D finally %7B%0A%09%09%09%09tx.commit();%0A%09%09%09%7D%0A
 %09%09%09ejb.em.cl
@@ -768,24 +768,24 @@
 em.close();%0A
-
 %09%09%7D%0A%09%09if (em
@@ -820,18 +820,17 @@
 %0A%09%09%7D%0A%09%7D%0A
-%09
 %0A
+
 %09@Test(e
@@ -1381,24 +1381,24 @@
 dMessage();%0A
-
 %09%09assertTrue
@@ -1459,11 +1459,598 @@
 e%22));%0A%09%7D
+%0A%0A%09@Test%0A%09public void testSetAndDelete() throws MessageException %7B%0A%09%09assertEquals(0, (long) ejb.em.createQuery(%22select count(m) from Message m%22).getSingleResult());%0A%0A%09%09EntityTransaction tx = ejb.em.getTransaction();%0A%09%09try %7B%0A%09%09%09tx.begin();%0A%09%09%09ejb.putUserMessage(%22hello%22);%0A%09%09%7D finally %7B%0A%09%09%09tx.commit();%0A%09%09%7D%0A%09%09assertEquals(1, (long) ejb.em.createQuery(%22select count(m) from Message m%22).getSingleResult());%0A%09%09%0A%09%09try %7B%0A%09%09%09tx.begin();%0A%09%09%09ejb.deleteMessage();%0A%09%09%7D finally %7B%0A%09%09%09tx.commit();%0A%09%09%7D%0A%09%09assertEquals(0, (long) ejb.em.createQuery(%22select count(m) from Message m%22).getSingleResult());%0A%09%7D
 %0A%7D%0A

Improve test coverage.