supernova
supernova

Reputation: 3261

How to make a jUnit4 test case class Spring Test case class?

I have a jUnit4 test case class ( extends TestCase). I am testing some code having Spring D.I and Hibernate. Somehow when i execute test ,looks like some internal transactions are rolling my test changes back. I am deleting a record using HibernateTemplate but nothing is getting deleted in database. I got a suggestion to make my test case transactional by making my class a Spring test class( using Spring Test Runner ) and use @Transactional attribute before method call. Can somebody please tell how can i make my Junit4 test class Spring test class? What configs do I need and which class to extend?

Thanks in advance.

Upvotes: 0

Views: 2175

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

Extend AbstractTransactionalJUnit4SpringContextTests or add these annotations to your test class:

@TestExecutionListeners(TransactionalTestExecutionListener.class)
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Everything about Spring testing is thoroughly explained in reference documentation.

The phenomenon you are experiencing is due the fact that Spring automatically wraps test methods in rollback-only transactions when test-case class is annotated with @Transactional. This has certain benefits: you won't corrupt your database during the test and each test works on the same data, so you are not introducing inter-test dependencies.

Upvotes: 0

Ritesh
Ritesh

Reputation: 7522

Extend AbstractJUnit4SpringContextTests. I highly recommend detailed reading of Testing chapter.

Upvotes: 0

Related Questions