1 package org.wamblee.support.persistence;
3 import javax.persistence.EntityManager;
4 import javax.persistence.Persistence;
5 import javax.sql.DataSource;
7 import org.dbunit.DataSourceDatabaseTester;
8 import org.dbunit.DatabaseTestCase;
9 import org.dbunit.IDatabaseTester;
10 import org.dbunit.dataset.ITable;
11 import org.dbunit.dataset.filter.ITableFilterSimple;
12 import org.junit.After;
13 import org.junit.Before;
14 import org.junit.Test;
15 import org.wamblee.support.persistence.DatabaseUtils;
16 import org.wamblee.support.persistence.JpaBuilder;
17 import org.wamblee.support.persistence.JpaTester;
18 import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
20 import static junit.framework.Assert.*;
24 * This class shows an example of how to test an entity using jpa.
26 public class MyEntityExampleTestBase {
28 // This is the magical object that does all the test setup.
29 private JpaTester jpaTester;
31 // The jpa tester initializes a lot for us....
33 // A JPA builder that provides a transaction scoped entity manager for us.
34 private JpaBuilder builder;
36 // The database tester for dbunit which is appropriately configured for our persistence unit.
37 private IDatabaseTester dbtester;
39 // Database utilities with some additional functionality for working with the databse
40 // such as dropping tables, cleaning tables, etc.
41 private DatabaseUtils dbutils;
44 public void setUp() throws Exception {
46 // First we create the JpaTester by telling us which persistence unit we are going to test
47 jpaTester = new JpaTester(new MyPersistenceUnit());
50 // Retrieve some useful objects fromt he jpa tester. It also provides direct access to the datasource
51 // but we don't need it. We can use datbase utils if we want to execute straight JDBC calls.
52 builder = jpaTester.getJpaBuilder();
53 dbtester = jpaTester.getDbTester();
54 dbutils = jpaTester.getDbUtils();
58 public void tearDown() {
63 public void testEntityPersistence() throws Exception {
65 // Use the JPA builder to create a transaction scoped entity manager for as and execute the
67 builder.execute(new JpaUnitOfWork<Void>() {
68 public Void execute(EntityManager em) {
69 MyEntity entity = new MyEntity("a", "b");
75 // Verify one row is written (using Db unit)
76 ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
77 assertEquals(1, table.getRowCount());
79 assertEquals("a", table.getValue(0, "SLEUTELTJE"));
80 assertEquals("b", table.getValue(0, "VALUE"));
82 // For this simple test, it can also be done through DatabaseUtils
83 assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));