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.*;
23 * This class shows an example of how to test an entity using jpa.
25 public class MyEntityExampleTestBase {
27 // This is the magical object that does all the test setup.
28 private JpaTester jpaTester;
30 // The jpa tester initializes a lot for us....
32 // A JPA builder that provides a transaction scoped entity manager for us.
33 private JpaBuilder builder;
35 // The database tester for dbunit which is appropriately configured for our
37 private IDatabaseTester dbtester;
39 // Database utilities with some additional functionality for working with
41 // such as dropping tables, cleaning tables, etc.
42 private DatabaseUtils dbutils;
45 public void setUp() throws Exception {
47 // First we create the JpaTester by telling us which persistence unit we
49 jpaTester = new JpaTester(new MyPersistenceUnit());
52 // Retrieve some useful objects fromt he jpa tester. It also provides
53 // direct access to the datasource
54 // but we don't need it. We can use datbase utils if we want to execute
55 // straight JDBC calls.
56 builder = jpaTester.getJpaBuilder();
57 dbtester = jpaTester.getDbTester();
58 dbutils = jpaTester.getDbUtils();
62 public void tearDown() {
67 public void testEntityPersistence() throws Exception {
69 // Use the JPA builder to create a transaction scoped entity manager for
72 builder.execute(new JpaUnitOfWork<Void>() {
73 public Void execute(EntityManager em) {
74 MyEntity entity = new MyEntity("a", "b");
80 // Verify one row is written (using Db unit)
81 ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
82 assertEquals(1, table.getRowCount());
84 assertEquals("a", table.getValue(0, "SLEUTELTJE"));
85 assertEquals("b", table.getValue(0, "VALUE"));
87 // For this simple test, it can also be done through DatabaseUtils
88 assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));