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.getDbTester();
65 dbutils = jpaTester.getDbUtils();
69 public void tearDown() {
74 public void testEntityPersistence() throws Exception {
76 // Use the JPA builder to create a transaction scoped entity manager for
79 builder.execute(new JpaUnitOfWork<Void>() {
80 public Void execute(EntityManager aEm) {
81 MyEntity entity = new MyEntity("a", "b");
87 // Verify one row is written (using Db unit)
88 ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
89 assertEquals(1, table.getRowCount());
91 assertEquals("a", table.getValue(0, "SLEUTELTJE"));
92 assertEquals("b", table.getValue(0, "VALUE"));
94 // For this simple test, it can also be done through DatabaseUtils
95 assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));