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.

18,028 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. Ugh moving — what a nightmare. Had my own horror story a couple months back and no joke I almost lost it. You start with boxes then suddenly youre drowning in clutter. Someone at work mentioned a company but I decided to look deeper. Long story short when youre hunting for a decent moving company in nevada dont settle for the first quote. Why? local nevada movers know the routes — particularly on narrow streets. I personally — called a bunch of places — and believe me it was 100 worth it. By the way this is the source that finally gave me clarity. nevada movers https://movers-in-nevada-pcq.com Just that resource cut through the noise. Rates are transparent — zero BS. I booked through them and they showed up on time. Do your due diligence. Confirm the timeline. Good movers turn chaos into routine. Wish I had found this sooner

  2. Давно искал приличного букмекера для беттинга. Протестировал много сайтов но всё-таки пришёл на данной БК. В обсуждениях упоминали — зашёл проверить. Короче говоря — достойный подход. Роспись плотная выплаты оперативные. В общем если ищете надёжную БК — рекомендую глянуть. Вот тут вся инф. 1win бонус за регистрацию 1win бонус за регистрацию И про зеркало актуальное — без лишней воды. Так же всё сделал — без заморочек. Не напряжно честно скажу. Вход через зеркало стабильный. Пробуйте сами. Спортивного везения

  3. Man moving is such a headache — dealt with this mess a few months ago and I swear I wanted to give up. You start packing then you realize how much junk youve accumulated. Neighbors suggested another but wanted to double-check. Long story short if youre looking for good moving services around here better compare a few options. Look local movers know the area especially with those narrow suburban streets. For instance — spent a week reading reviews — and trust me it was totally worth it. So check this out where the best option popped up. moving companies nevada https://movers-in-nevada.com Honestly that resource saved me hours of scrolling. They have transparent rates — straight to the point. Ended up booking and they handled it professionally. Do your due diligence. Check the credentials. Quality service is priceless. Wish I had this info earlier

  4. Moving is always a hassle — just went through it a recently and honestly I almost lost it. It seems easy at first then bam — you realize how much junk youve got. Coworker used someone else but I wasnt going to trust blindly. Anyway: when youre looking for reliable moving services around here compare at least a few. Because companies here handle the weather better — especially with long distances. I personally — asked about insurance and extra fees — and trust me that homework saved me big time. This is the resource that helped me lock in a good choice. moving companies nevada moving companies nevada Honestly that list cut my search in half. Prices are up front — straightforward rates. Booked through that link and zero issues from start to finish. Be smart about this. Check their credentials. Quality service is worth every dollar. Wish I had this info earlier

  5. Oh man relocating is pure torture. Went through it just recently and honestly what a disaster. Seems easy enough then it hits you how much crap you own. Someone online praised one company but I dug deeper myself. So heres the deal: when youre on the hunt for a reliable moving company in nevada dont just take the first price. The thing is companies here handle the summer heat better — especially in Vegas traffic. For example — checked their licensing — and believe it or not I avoided a huge headache. This is the page that helped me lock in a good one. nevada moving services https://movers-in-nevada-xhr.com That one spot made everything obvious. Rates are transparent — straight pricing. Went with their top recommendation and it went flawlessly. Dont rush into this. Check the credentials. A good mover makes moving boring. Good luck with your move

  6. Люди подскажите Муж просто потерял себя Жена в истерике В больницу тащить страшно Короче только это реально спасло — вывод из запоя на дому недорого с гарантией Сняли ломку и стабилизировали состояние В общем телефон и цены тут — алкоголь вывести из запоя люберцы https://chastnyj.vyvod-iz-zapoya-na-domu-moskva.ru Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  7. Moving is a whole production — went through this a few months ago and honestly quite the ordeal. You grab some boxes then youre swimming in clutter. A buddy used one outfit but I didnt want to gamble. Anyway: when you need a decent moving company in nevada compare several options. Heres the deal: local nevada movers know the territory — especially in summer. Heres what worked for me — asked about insurance and all the fees — and trust me that extra effort was a lifesaver. Heres the link that helped me find the right fit. nevada long distance movers https://movers-in-nevada-mtw.com Honestly that resource gave me what I needed. Rates are shown upfront — clear quotes. Set up my whole move and absolutely no problems. Take your time. Ask about licensing. Good service is worth every cent. Best of luck with your move

  8. Давно искал достойную платформу для игры. Протестировал много сайтов но всё-таки пришёл на 1вин. Коллеги рекомендовали — захотелось оценить. И вот что понял — достойный подход. Линия широкая расчёты быстрые. Суть в том если хотите нормально ставить — смело заходите. Вот тут вся инф. 1win официальный сайт 1win официальный сайт И про зеркало актуальное — комплексно. Так же всё сделал — на удивление просто. Регистрация минутная верификация простая. Если основной сайт блокнут — есть выход. Так что не тяните. Спортивного везения

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>