I have a lifecycle issue running a test suite using JUnit.
To write convenient test tests JPA 2.0 As a Java developer I want:
- Initialize an EntityManagerFactory instance once before all test suites. I reach the object using @BeforeClass annotation
- Create an instance of EntityManager and start a new transaction before each test case and roll back the started transaction, such as AOP before / after or around the board.
- Be able to perform any installation / break operations before / after in any derived set of tests
I wrote a lot of JUnit tests. But in this case, I have problems with the second and third items from the list.
Please take a look at the following test suite examples:
Abstract test suite :
public abstract class AbstractPersistenceTest {
protected static EntityManagerFactory emf;
protected EntityManager em;
@BeforeClass
public static void setUpClass() {
emf = Persistence.createEntityManagerFactory("test");
}
@Before
public void setUp() {
em = emf.createEntityManager();
em.getTransaction().begin();
}
@After
public void tearDown() {
em.getTransaction().rollback();
em.close();
}
@AfterClass
public static void tearDownClass() {
emf.close();
}
}
:
public class EmployeeJpqlTest extends AbstractPersistenceTest {
private Employee john;
private Employee jack;
@Before
public void setUp() {
john = new Employee("John Doe", 1000);
jack = new Employee("Jack Line", 1010);
em.persist(john);
em.persist(jack);
}
@Test
public void itShouldRetrieveAllEmplloyees() {
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e",
Employee.class);
List<Employee> employees = query.getResultList();
assertArrayEquals(new Employee[] { john, jack }, employees.toArray());
}
@Test
public void itShoulRetrieveAllEmployeeNames() {
TypedQuery<String> query = em.createQuery(
"SELECT e.name FROM Employee e", String.class);
List<String> names = query.getResultList();
assertArrayEquals(new String[] { john.getName(), jack.getName() },
names.toArray());
}
}
- JUnit NullPointerException setUp() . .
start/rollbacking setUp()/tearDown() ?
, , JUnit, ?
.