Book Image

SPRING COOKBOOK

By : Jerome Jaglale, Yilmaz
Book Image

SPRING COOKBOOK

By: Jerome Jaglale, Yilmaz

Overview of this book

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.
Table of Contents (14 chapters)
13
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)