667514 members! Sign up to stay informed.

Sponsored Links


Resources

Enterprise Java
Research Library

Get Java white papers, product information, case studies and webcasts

News News News Messages: 5 Messages: 5 Messages: 5 Printer friendly Printer friendly Printer friendly Post reply Post reply Post reply XML XML XML

Unitils 1.1 adds support for JPA

Posted by: Filip Neven on August 28, 2008 DIGG
Unitils helps you in writing simple and maintainable unit and integration tests with JUnit or TestNG. It glues together popular test libraries like DbUnit and EasyMock and offers integration with
Spring and Hibernate. Unitils encourages applying good practices and testing guidelines. The ideas behind it are based on the authors' concrete experience on enterprise projects.

In the 1.1 release, support has been added for writing tests for code that makes use of the Java Persistence API (JPA), in a very similar way as already available for Hibernate. In what follows, we'll demonstrate these features using a simple example.

Code example

Suppose we have a PersonRepository interface with an implementation based on JPA. The PersonRepository interface has a method findByLastName and is implemented as follows:

public class PersonRepositoryImpl implements PersonRepository {

@PersistenceContext
private EntityManager entityManager;

public List<Person> findByLastName(String lastName) {
List<Person> persons = entityManager.createQuery("find person from Person person where person.lastName = :lastName").getResultList();
return persons;
}
}

We've written following test for this method:

@JpaEntityManagerFactory(persistenceUnit = "test", configFile = "META-INF/persistence-test.xml")
@Transactional(TransactionMode.COMMIT)
@DataSet
public class PersonRepositoryImplTest extends UnitilsJUnit4 {

@PersistenceContext
EntityManager entityManager;

PersonRepository personRepository = new PersonRepositoryImpl();

@Before
public void init() {
JpaUnitils.injectJpaResourcesInto(personRepository);
}

@Test
public void testSearchByLastName() {
List<Person> result = personRepository.findByLastName("Doe"));
ReflectionAssert.assertPropertyLenEquals("firstName", Arrays.asList("John", "Jane"), result);
}
}

You'll notice that this test extends UnitilsJUnit4. This makes sure that while running the test, unitils can hook into the execution of the test and inspect the test for annotations that ask for extra behavior to be performed. For JUnit version 3.x and TestNG, we offer similar base classes called UnitilsJUnit3 and UnitilsTestNG.


JPA configuration

The @JpaEntityManagerFactory annotation tells where to find the JPA persistence config file that needs to be loaded and the name of the persistence unit to load. If hibernate is configured as the persistence provider, the persistence config file could look as follows:

<persistence xmlns="http://java.sun.com/xml/ns/persistence">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">

<persistence-unit name="test">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>

You don't need to configure the DataSource in the test persistence config file. Under the hoods, care is taken that the JPA persistence context connects with the test database configured in unitils.

Unitils offers a simple way to separate shared project and local configuration: common configuration is stored in a file unitils.properties located in the classpath, and developer specific configuration in a local file preferably stored in the user home dir. This enables every developer to configure make sure he uses his own database (schema). We advise to provide a test database (or schema) for each developer, which avoids conflicts and enables each database to evolve on its own pace.

This is not the only possible way of configuring an EntityManagerFactory: If you're using Spring, you can make use of an EntityManagerFactory configured in a spring config file in your tests. For more information on this subject, check the documentation.


Other features of unitils

Unitils offers even a lot more: By annotating tests with @Transactional, every test is configured to run in a transaction which can be committed or rolled back at the end. A powerful system is also offered to automatically maintain every developer's test database.

The reflection assert utility enables checking if the resulting object matches the expected one by scanning the complete object graph using reflection, with the ability of ignoring fields that are null in the expected object, ignoring the type and order of collections and the specific value of dates. In unitils 1.1, the reflection assert utility has been improved to make sure it gives a detailed, user friendly overview of all the differences between the expected and actual object.

If you want to learn more about unitils, check out the tutorial and cookbook. If you have any comments, tips or questions, don't hesitate to post them on the user forum.

Threaded replies

·  Unitils 1.1 adds support for JPA by Filip Neven on Thu Aug 28 13:22:56 EDT 2008
  ·  Looks very interesting by Mr Magoo on Thu Aug 28 17:57:34 EDT 2008
  ·  Re: Unitils 1.1 adds support for JPA by greg matthews on Thu Aug 28 20:01:37 EDT 2008
    ·  Re: Unitils 1.1 adds support for JPA by Filip Neven on Fri Aug 29 02:37:39 EDT 2008
      ·  Re: Unitils 1.1 adds support for JPA by greg matthews on Sun Aug 31 23:56:47 EDT 2008
  ·  It works well by Jon Alvarado on Wed Sep 03 01:21:01 EDT 2008
  Message #267576 Post reply Post reply Post reply Go to top Go to top Go to top

Looks very interesting

Posted by: Mr Magoo on August 28, 2008 in response to Message #267543
Definitely a technology I will be checking out. Sounds great.

I am sure you will pick up flak from the TDD fanatics for supporting tests that are not real unit tests. :)

Having said this I do have a small gripe. Your assertion for equals via reflection is very poorly chosen.
assertRefEquals read (to me anyways) as assertReferenceEquals.

I guess it is a 5 minute confusion thing anyways.

  Message #267577 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Unitils 1.1 adds support for JPA

Posted by: greg matthews on August 28, 2008 in response to Message #267543
If you use named query annotations, and put queries at the top of each entity class then they're automatically syntax checked when the persistence context is loaded.

You can also fairly easily test the JPA layer with the Spring Abstract DI test class -- just make sure you've structured the Spring XML files such that the DAO layer can be booted up cleanly.

  Message #267580 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Unitils 1.1 adds support for JPA

Posted by: Filip Neven on August 29, 2008 in response to Message #267577
If you use named query annotations, and put queries at the top of each entity class then they're automatically syntax checked when the persistence context is loaded.

You can, but this is only syntax checking; it is useful to also have functional tests for your data access layer. Besides, I prefer to simply have my queries on the DAO/Repository, where they belong, instead of polluting my entities with them.

You can also fairly easily test the JPA layer with the Spring Abstract DI test class -- just make sure you've structured the Spring XML files such that the DAO layer can be booted up cleanly.

Unitils also supports working with a spring configured EntityManagerFactory, but indead you can also simply use spring's testing framework. The reason for still choosing unitils could then be for it's dbunit integration and automatic database maintenance features.
Later this year we'll provide integration between spring's testing framework and unitils, so that you can make use of unitils' extra features in tests written with spring's framework.

  Message #267665 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Unitils 1.1 adds support for JPA

Posted by: greg matthews on August 31, 2008 in response to Message #267580
If you use named query annotations, and put queries at the top of each entity class then they're automatically syntax checked when the persistence context is loaded.

You can, but this is only syntax checking; it is useful to also have functional tests for your data access layer. Besides, I prefer to simply have my queries on the DAO/Repository, where they belong, instead of polluting my entities with them.



I see the point you're making about putting queries in the a DAO class. I still prefer to put as many queries as possible as named queries in the actual entity, which seems to be the approach promoted by the JPA spec -- since there's an annotation for it!

I'll check out DBUnit too, but previously I've run Dao tests by having 'unit' tests run against HSQL in-memory with auto-create of tables, and the full app start up against a proper db.

Its a PITA to do with JPA, i.e. have unit tests use a different DB to the full running app, but with a bit of a hack, and subclassing of some Spring/JPA related classes you can do it.

  Message #267836 Post reply Post reply Post reply Go to top Go to top Go to top

It works well

Posted by: Jon Alvarado on September 03, 2008 in response to Message #267543
I've been using Unitils with my projects and it works really well. I have tried in the past to use an HSQL embedded database but always ran into compatibility problems when any nonstandard sql was used. In typical J2EE apps an extremely large portion of the regression testing involves the database integration and Unitils helps you with this. Using Unitils running against a empty database populated with data created specifically to test your methods gives you a high level of confidence that you have a correctly running application. The automatic database xsd schema generation that integrates with dbunit makes it easier to test your DAO layer than writing your own SQL inserts for one-off tests, especially given that the DBMaintainer removes all the database constraints for you. The Spring support annotations are also far easier to understand and use than the standard Spring base classes for test cases.

New content on TheServerSide.comNew content on TheServerSide.comNew content on TheServerSide.com

Dependency Injection in Java EE 6 - Part 1

Reza Rahman explores the features of the proposed JSR 299, Contexts and Dependency Injection for Java EE (CDI). When approved, it promises to be a key feature of Java EE 6. (November 2, Article)

SAML: It's Not just for Web services

SAML is an XML-based standard for exchanging authentication and authorization data between security domains. The single most important problem that SAML was created to solve is the Web browser Single Sign-On problem. Many organizations are debating whether to stay with version 1.1 or move to 2.0. This article makes observations about both options. (September 28, Article)

Programming is Also Teaching Your Team

Joe Ottinger takes a look at how people learn, and applies it to the practice of programming. He notes that understanding how people learn is an essential part of working in a programming team. (September 22, Article)

Can Java EE Deliver The Asynchronous Web?

Stephen Maryka gave us an article about the Asynchronous Web and posed a number of questions that get examined like an approach to delivering Asynchronous Web capabilities through extensions to existing Java EE technologies. (July 14, Article)

JSF Flex

JavaServer Faces Flex goal is to provide users capability in creating standard Flex components, part of flexSDK which is open sourced through MPL license, as normal JSF components. This article by Ji Hoon Kim will provide an overview of creating a simple multilingual JSF page consisting of JSF Flex tags. (June 29, Article)

The Rules of SOA - A Road to a Successful SOA Implementation

In this session Jeff explores the key characteristics of successful SOA projects. He covers some of the patterns, and anti-patterns, tool sets, and strategies that he himself learned the hard way. Last, he provides a strategy and blueprint for achieving a high likelihood of success in your SOA project. (June 23, Tech Talk)

Ari Zilka Talks About Terracotta 3.1

Ari Zilka, CTO of Terracotta, Inc., talks about the new features in Terracotta 3.1, announced during JavaOne and available now. (June 15, Tech Talk)

Enterprise Application Integration, and Spring

In this Tech Talk, Josh Long explores an integration challenge using Spring Integration and walks through the implementation, employing and expanding on the basic patterns of Enterprise Application Integration to tie together components into a function integration solution, and then demonstrates how Spring Integration helps address the integration requirements. (June 15, Tech Talk)

Google Web Toolkit: An Introduction

In this Tech Talk, David Geary teaches you: The basics of Google Web Toolkit; How to implement Ajax-enabled applications in Java; Internationalization; Hooking into the browser history mechanism; Remote procedure calls. (June 4, Tech Talk)

Just Enough Early Architecture to Guide Development

Jon Kern discusses the best architecture/technical solutions and ensure that they are repeated by all developers. By tackling the architecture up-front in a serial manner, subsequent parallel development will be much more manageable and predictable. (May 28, Tech Talk)

Productive Programmer: On the Lam from the Furniture Police

This keynote describes the frustrations of modern knowledge workers in their quest to actually get some work done, and solutions for how to guard yourself against all those distractions. Neal Ford talks about environments, coding, acceleration, automation, and avoiding repetition as ways to defeat the misguided attempts to sap your ability to produce good work. (May 26, Tech Talk)

Auto-Scaling Your Existing Web Application

Gil demonstrates how new, aggressive uses of already abundant compute capacity by common applications offer competitive value for application designers. (May 21, Tech Talk)

Automating Hibernate Mapping and Queries For Java Web Development

Chris Keene introduces WaveMaker as a new way to automate the ability to generate Hibernate classes in order to more quickly bring OR mapping into an application. (May 19, Article)

Auto-Scaling Your Existing Web Application

In this session Nati Shalom demonstrates how to take a standard Java EE web application and scale it out or down dynamically without changes to the application code. Seeing as most web applications are over-provisioned to meet infrequent peak loads, this is a dramatic change because it enables growing your application as needed, when needed, without paying for unutilized resources. (May 19, Tech Talk)

Free Book: Jakarta-Struts Live

Download the entire book of Jakarta-Struts Live and learn about Struts MVC, Tiles, the Validator, DynaActionForms, plug-ins, internationalization, and more.
(Book PDF Download)

Application Server Matrix

The Application Server Matrix is a detailed listing of J2EE vendors and their application server products, with information on latest version numbers, J2EE spec support and licensing, pricing, platform support, and links to product downloads and reviews.
(Application Server Comparison Matrix)

News | Blogs | Discussions | Tech talks | Patterns | Reviews | White Papers | Downloads | Articles | Media kit | About
Java Solutions
All Content Copyright ©2007 TheServerSide Privacy Policy
Site Map