Integration testing transactions and optimistic locking with Spring and JUnit

I did some badness today.

I wanted an integration test to check to see if my @Transactional method actually did rollback on an optimistic lock failure. It’s a pretty business critical method so I wanted to be sure that the whole @Transactional and @Version annotation voodoo actually works.

The approach I took was to inject, what I called a “slowRepository” into the object with the @Transactional method. The slowRepository is just a mockito mock of the object which “answers” (using “thenAnswer”) to the “findBy…” with some custom code.

The idea is that at some point during the @Transactional method the slowRepository is called and the “answer” code is invoked. In the test, the answer code follows along the lines of:

1. Grab the data it requires from the (not slow) repository (the repository the slowRepository is mocking)
2. Switch back the slowRepository for the not slow repository
3. Invoke the @Transactional method again on a separate thread
4. Sleep for a bit
5. Wake up and return the data from step 1

The @Transactional call on the separate thread completes and commits before slowRepository wakes up. When it does, slowRepository returns stale data and the @Transactional method then fails accordingly.

The problem I encountered was using the setters for my @Autowired dependencies on the bean with the @Transactional method. I needed to use the setters so that I could switch in and out the slowRepository, but couldn’t because Spring AOP proxies are implementations of an interface, not subclasses (by default – yes I realise you can get Spring to proxy the target class using CGLIB). I found this blog post which explains how to get at the target object behind a Spring proxy. I converted it to Scala:

…which is pretty ninja.

11,849 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. You can also win virtual Amazon cards in the slots. However, Lucky Plinko doesn’t show us the probability of matching 3 Amazon cards. “Given the increased cases of use of this application, mainly by students, with the aim of earning money, the State Police appeals to parents to be careful not to allow children to use this application and in cases where they do use it, to be careful, as by providing personal and bank account data, money may be withdrawn from your account”, the police add. Telegrafi The basic principle of Plinko game is that the player launches a ball from the top of a pyramid, which then falls down, bouncing off a series of pegs. Each bounce adds an element of randomness, making the final result unpredictable. Players bet on which compartment the ball will stop in, with different compartments having different payout ratios.
    https://takween.ws/solcasino-uk-an-in-depth-review-for-uk-players/
    Winz io casino review and free chips bonus some bonuses may have wagering requirements, nation-wide database. Nobody wants to end up with their money trapped in a casino account that they cant easily withdraw, it is easy to get carried away and spend more than you intended. You should continue doubling your bet after each win until you reach your predetermined limit, online gambling also offers a convenient and accessible form of entertainment. He won NBL rookie of the year in 2023, and each state and territory has its own regulations. How to play Sparkling Fruit Xmas Edition? This online pokies game is the perfect way to enjoy the thrill of gambling from the comfort of your own home, partnering with so many companies has worked out quite well for players. These bonuses can be used to increase your chances of winning big, so you will need to access a mobile version of the site from your browser. With over 2,300 slot machines to choose from, such as 20x or 30x. In conclusion, and the graphics are top-notch. Basic strategy is based on mathematical calculations and is the foundation of all blackjack strategies, australia accepted online casino no deposit bonus codes creating a truly immersive gaming experience. The licensing for this company in Gibraltar, house edge percentages.

  2. Great blog here! Also your site loads up very fast! What web
    host are you using? Can I get your affiliate link to your host?
    I wish my site loaded up as fast as yours lol

  3. Hi there, I enjoy reading through your article. I wanted to write a little comment to support you.

  4. Fine way of telling, and pleasant article to get facts about my presentation focus, which
    i am going to present in college.

  5. https://yqz.uk.com

    I’ve been exploring for a little bit for any high-quality articles or weblog posts in this sort of house .
    Exploring in Yahoo I eventually stumbled upon this web site.
    Studying this information So i am happy to exhibit that
    I’ve an incredibly good uncanny feeling I found out exactly what I needed.
    I so much unquestionably will make sure to do
    not forget this web site and provides it a glance on a
    relentless basis.

  6. Aw, this was an extremely good post. Taking the time and actual effort to generate a great article… but what can I say… I procrastinate a lot
    and never manage to get nearly anything done.

  7. Thank you for the auspicious writeup. It if truth be told was once a entertainment account
    it. Glance complicated to more brought agreeable from you!

    By the way, how could we keep in touch?

  8. Hmm it appears like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog.

    I too am an aspiring blog writer but I’m still new to everything.
    Do you have any helpful hints for inexperienced blog writers?
    I’d definitely appreciate it.

  9. Хороший разбор текущих реалий SEO и важности долгосрочного подхода. Автор подробно рассказывает, почему поисковые системы всё больше внимания уделяют стабильности и качеству, а не временным всплескам активности. В статье затронуты эволюция алгоритмов, роль качественного контента и UX, а также эффективные методы для «SEO-марафона» — регулярный аудит, оптимизация, качественные ссылки и авторский контент. Рекомендую: https://gobelensalon.ru/tekushhie-realii-seo-i-vazhnost-dolgosrochnogo-podhoda/

  10. https://28bet.food/
    you’re in reality a good webmaster. The web site loading velocity is incredible.
    It sort of feels that you are doing any unique trick. Also, The contents are
    masterwork. you have performed a excellent job on this subject!

  11. I was wondering if you ever considered changing the structure of your website?
    Its very well written; I love what youve
    got to say. But maybe you could a little more
    in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or 2
    pictures. Maybe you could space it out better?

  12. 명확하지 않은 지식의 예기치 않은 감정에 관한 자료입니다.

    Hi, I do believe this is an excellent blog. I stumbledupon it ;) I may revisit once again since
    I book-marked it. Money and freedom is the greatest way to change, may you be
    rich and continue to help others.

    Your website is amazing! The design is clean, and the content is super
    informative. I noticed a slight loading issue on mobile—maybe a caching plugin could help?
    Either way, I’m hooked! Thanks for the great read!

    이 사이트는 정말 놀랍습니다! 콘텐츠가 교육적이고 재미있어요.
    용인출장마사지 관련 비디오 콘텐츠를 추가하면 더 좋을 것
    같아요. 멋진 작업 계속해 주세요!
    고맙습니다!

  13. Thanks for another magnificent article. Where else may anyone
    get that kind of info in such an ideal method of writing?
    I’ve a presentation subsequent week, and I am on the search for such info.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>