Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Unit testing with transactions


To test a DAO class, for example, you will need to perform database queries that won't be persisted. For example, to test the DAO method to add a user, you want to make sure that the user is actually created in the database, but you don't want that test user to remain in the database. Transactions help you to do this with minimum effort.

How to do it…

Follow these steps to automatically revert the database modifications performed by a test method:

With TestNG, make the test class extend:

public class UserDAOTest extends AbstractTransactionalTestNGSpringContextTests  {
...

With JUnit, add the @Transactional annotation to the test class:

@Transactional
public class UserDAOTest {
...

How it works…

Each test method of the class will automatically:

  • Start a new transaction

  • Execute as normal

  • Rollback the transaction (so any modifications to a database will be reverted)