2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.support.persistence;
18 import static junit.framework.Assert.*;
20 import javax.persistence.EntityManager;
22 import org.dbunit.IDatabaseTester;
23 import org.dbunit.dataset.ITable;
24 import org.junit.After;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
30 * This class shows an example of how to test an entity using jpa.
32 public class MyEntityExampleTestBase {
34 // This is the magical object that does all the test setup.
35 private JpaTester jpaTester;
37 // The jpa tester initializes a lot for us....
39 // A JPA builder that provides a transaction scoped entity manager for us.
40 private JpaBuilder builder;
42 // The database tester for dbunit which is appropriately configured for our
44 private IDatabaseTester dbtester;
46 // Database utilities with some additional functionality for working with
48 // such as dropping tables, cleaning tables, etc.
49 private DatabaseUtils dbutils;
52 public void setUp() throws Exception {
54 // First we create the JpaTester by telling us which persistence unit we
56 jpaTester = new JpaTester(new MyPersistenceUnit());
59 // Retrieve some useful objects fromt he jpa tester. It also provides
60 // direct access to the datasource
61 // but we don't need it. We can use datbase utils if we want to execute
62 // straight JDBC calls.
63 builder = jpaTester.getJpaBuilder();
64 dbtester = jpaTester.getDbUtils().createDbTester(new MyTables());
65 dbutils = jpaTester.getDbUtils();
70 public void tearDown() {
76 public void testEntityPersistence() throws Exception {
78 // Use the JPA builder to create a transaction scoped entity manager for
81 builder.execute(new JpaUnitOfWork<Void>() {
82 public Void execute(EntityManager aEm) {
83 MyEntity entity = new MyEntity("a", "b");
89 // Verify one row is written (using Db unit)
90 ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
91 assertEquals(1, table.getRowCount());
93 assertEquals("a", table.getValue(0, "SLEUTELTJE"));
94 assertEquals("b", table.getValue(0, "VALUE"));
96 // For this simple test, it can also be done through DatabaseUtils
97 assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));