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.

12,269 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. I do not even know how I stopped up right here, but I assumed this publish was good.
    I don’t understand who you’re but definitely you are going
    to a famous blogger if you happen to aren’t already.
    Cheers!

  2. Admiring the time and energy you put into your site and detailed information you offer.
    It’s good to come across a blog every once in a while that isn’t the same old rehashed material.
    Excellent read! I’ve bookmarked your site and I’m adding your RSS feeds
    to my Google account.

  3. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added
    I get three emails with the same comment. Is there any way you
    can remove people from that service? Thank you!

  4. Wonderful article! That is the kind of info that are supposed to be shared around the internet.

    Disgrace on the seek engines for no longer positioning
    this put up upper! Come on over and discuss with my website .
    Thanks =)

  5. What i do not understood is in fact how you are not actually much more smartly-favored than you might
    be now. You’re so intelligent. You know therefore considerably in the case of this matter,
    made me individually consider it from a lot of various angles.
    Its like women and men are not involved until it’s one thing to accomplish with Lady gaga!
    Your individual stuffs great. At all times deal with it up!

  6. سلام، خودم دیروز به صورت کاملا تصادفی تو اینترنت با این وبسایت برخوردم و واقعا خیلی خوشم اومد.
    نوشته‌هاش جذاب بودو خیلی کم پیش میاد همچین وبسایتی ببینم.
    فکر کنم برای خیلی‌ها کاربردی باشه.
    برای کسایی که دنبال اطلاعات کامل هستن
    پیشنهاد می‌کنم حتما برن ببینن.
    در مجموع تجربه خوبی بود و قطعا باز هم
    سر می‌زنم

    در آخر کار

    برای کاربرایی که در جستجو هستن

    کازینو اینترنتی

    وقت صرف می‌کنن

    این سیستم آنلاین

    خیلی راحت می‌تونه

    مناسب باشه

    جالب‌تر اینکه

    وبسایت‌هایی مثل

    enfеjar online

    و

    sibbet قوی

    در بین کاربران شناخته شدن

    به طور کلی

    قابل توجه بود

    و

    به احتمال قوی

    استفاده خواهم کرد

    .

    Have a look at mmy homepаge :: تحلیل بنیادی –
    Sibbb.net.tr -

  7. When I originally left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and now every
    time a comment is added I get four emails with the exact same comment.
    There has to be a means you are able to remove me from that service?
    Thank you!

  8. Hi i am kavin its my first occasion to commenting anywhere when i read this paragraph i thought i could also make comment due to this sensible paragraph. no deposit bonus

  9. Why visitors still make use of to read news papers when in this technological world the whole thing is accessible on net? no deposit bonus

  10. Thank you for the good writeup. It in fact
    was a amusement account it. Look advanced to more added agreeable from
    you! By the way, how can we communicate?

  11. По теме “Актуальные события и жизни Курганской области”, есть отличная статья.

    Вот, можете почитать:

    https://45media.ru

  12. Thanks a lot for sharing this with all people you actually recognize what youre talking about Bookmarked. Kindly also seek advice from my site =). We can have a link alternate agreement among us no deposit bonus

  13. My brother recommended I might like this blog. He was once totally right.
    This submit truly made my day. You can not
    believe just how much time I had spent for this info! Thanks!

  14. For most recent information you have to pay a visit world wide web and on internet I found this web site as a best site for newest updates. free spins no deposit

  15. Hi there just wanted to give you a quick heads up and let you know a few of the pictures arent loading properly. Im not sure why but I think its a linking issue. Ive tried it in two different web browsers and both show the same results. no deposit bonus

  16. USA LIVE IPTV worked flawlessly across Fire TV Stick, Smart TVs, Android TV Box,
    Roku, Apple devices, MAG Box, dedicated IPTV
    boxes, Windows PCs, smartphones, tablets, and laptops Solution: Installing widely compatible apps
    such as VLC, Kodi, or.

  17. Hi there to all how is all I think every one is getting more from this web page and your views are fastidious in support of new viewers. no deposit bonus

  18. Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way Ill be subscribing to your feeds and even I achievement you access consistently rapidly. free spins no deposit

  19. Pretty component to content. I simply stumbled upon your website and in accession capital to claim that I get in fact enjoyed account your blog posts. Any way I will be subscribing in your feeds and even I achievement you get admission to consistently rapidly. no deposit bonus

  20. Whats up all is going well here and ofcourse every one is sharing information thats really fine keep up writing. free spins no deposit

  21. Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didnt appear. Grrrr… well Im not writing all that over again. Anyhow just wanted to say great blog no deposit bonus

  22. Good day I am so excited I found your blog page I really found you by mistake while I was researching on Bing for something else Nonetheless I am here now and would just like to say thank you for a tremendous post and a all round thrilling blog I also love the theme/design I don’t have time to go through it all at the moment but I have saved it and also added your RSS feeds so when I have time I will be back to read much more Please do keep up the excellent b. free spins no deposit

  23. Почему пользователи выбирают площадку KRAKEN?

    Маркетплейс KRAKEN заслужил доверие многочисленной
    аудитории благодаря сочетанию ключевых
    факторов. Во-первых, это широкий и разнообразный ассортимент,
    представленный сотнями продавцов.
    Во-вторых, интуитивно понятный интерфейс KRAKEN, который упрощает
    навигацию, поиск товаров и
    управление заказами даже для новых
    пользователей. В-третьих,
    продуманная система безопасных транзакций, включающая механизмы разрешения споров (диспутов) и возможность использования условного депонирования, что минимизирует риски для обеих сторон сделки.
    На KRAKEN функциональность сочетается
    с внимательным отношением к безопасности клиентов, что делает процесс покупок более предсказуемым, защищенным
    и, как следствие, популярным среди пользователей, ценящих анонимность и надежность.

  24. Hello there, just became aware of your blog through Google,
    and found that it’s really informative. I am gonna watch out for brussels.
    I’ll be grateful if you continue this in future. Many people will be benefited from your writing.
    Cheers!

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>