views:

336

answers:

2

I'm writing a test to see if my getHibernateTemplate().delete(x) works. Now I've discovered that in a single test there seems to be some caching (my test class extends extends AbstractTransactionalDataSourceSpringContextTests).

What I mean is the following. My delete function:

does it exist? yes: delete it and return true no: return false.

Now I try to do two asserts in my test function. the first is an assertTrue to check if it's actually deleted the second is an assertFalse to see that it correctly returns false.

However my second test fails, and when I debug it it does indeed go to the true section.

However if I add the following line getHibernateTemplate().find("from classX"); as the first line in the delete function it works as intended. Even though I do nothing with the value. So a caching problem seems to be the most logical.

Does anyone have any advice, because leaving the line in there seems a bit dirty.

A: 

Just a thought, you might be falling over the fact that the all the invokations to getHibernateTemplate().dosomething() are happening in the same transaction. I have had problems before where tests that in production would result in two transactions ended in the same transaction in my unit tests due to AbstractTransactionalDataSourceSpringContextTests.

This resulted in entities already being associated with the hibernate session on the second invokation, which could provide a pointer as to what might be going on.

But it's been a while since I've looked at this, so I might be wide of the mark here.

beny23
Yes, it's in the same transaction.Thanks to your and jboy'ds post I've found an answer.An endTransaction() in my test does the trick.
+1  A: 

I don't have the library on my computer currently so I can't tell you the exact code, but I think you need to detach the session.

getSharedEntityManager().flush(); //it's something like this
getSharedEntityManager().clear(); 

that will clean out the transaction and begin a new one so you can make better assumptions. I have found the the test suite which you are extending has some very odd inconsistencies with caching, so it's not just you.

walnutmon