Tuesday 13 December 2011

Spring and the transaction annotation (part1)

Okay, I know this is documented in the spring documentation, but it's easy to forget and it can really trip you up, but if you are calling from within a class to another method on the same class that is marked as transactional you won't get the transaction you are expecting.

But how are you supposed to catch these bugs in test code? Easy mock comes to the rescue again....

Let me explain

Spring has made it really easy to test your code. It ships with a full test harness and enables you to override the classpath with certain resources when running certain testcases. So how does this help?
Well, mock out the jpa layer! That way you can see AND TEST when a transaction starts and when it ends.

  

so that basically says to Spring "hey, if you want to use that entity manager bean, you know, the one that implements javax.persistence.EntityManagerFactory, then use EasyMock's factory method called 'createStrickMock'."

so how does this work in code then?

I'll get to that in part 2!

Vargs bites agian

This caught me out the other day. Perhaps it shouldn't have done, but I thought it was interesting enough to write down.

The method looked like
public void myMethod(String... something);

I was trying to mock it out and was expecting it to be called with an empty argument list...

I initially tried to clever and though, "well, I know that arguments are autoboxed into an array, so I guess this will happen"
     EasyMock.expect(myObject.myMethod(EasyMock.arrEq(String[]{})));


hmmmm... no joy.... it went pop at runtime...

turns out that vargs is even more surprising that I first thought....

the expectation I was looking for was
     EasyMock.expect(myObject.myMethod());

simple when you've seen it!