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.

13,093 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. Между прочим, если вас интересует Фанатские мнения и отчеты о спортивных баталиях, посмотрите сюда.

    Ссылка ниже:

    https://fan-arsenal.ru

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

    به شکل خلاصه

    برای کسانی که میخوان

    بازی‌های آنلاین پولی

    علاقه دارن

    این برند

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

    ارزش امتحان داشته باشه

    از سوی دیگر

    دامنه‌هایی مثل

    پلتفرم enfejaronline

    و

    برند ѕibbet

    تونستن اعتماد جلبکنن

    در نهایت

    خیلی خوب بود

    و

    بدون تردید

    بازدیدش می‌کنم

    .

    My weЬ site سایت آی تی

  3. I like the valuable info you provide in your articles.
    I’ll bookmark your blog and check again here frequently.
    I am quite sure I’ll learn many new stuff right here!
    Best of luck for the next!

  4. Its like you read my mind! You seem to know so much about this,
    like you wrote the book in it or something. I think that you could
    do with some pics to drive the message home a little bit, but other
    than that, this is excellent blog. A great read. I’ll definitely be back.

  5. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail.
    I’ve got some suggestions for your blog you might be interested in hearing.
    Either way, great site and I look forward to seeing it
    expand over time.

  6. در جمع‌بندی نهایی

    برای کسانی که

    بازی‌های کازینویی

    تمایل دارن

    این شبکه

    می‌تونه مناسب باشه

    مفید باشه

    چیزی که جلب توجه می‌کنه اینه که

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

    enfejaronline جدید

    و

    sibbеt آنلاین

    جایگاه خوبی دارن

    در جمع‌بندی

    رضایت‌بخش بود

    و

    احتمالاً

    بازم میام

    Feel free to viѕit my blog پروژه دانشجویی

  7. An impressive share! I have just forwarded this onto a coworker
    who had been conducting a little research
    on this. And he in fact ordered me dinner due to the fact that I stumbled upon it for him…

    lol. So allow me to reword this…. Thanks for the meal!!
    But yeah, thanks for spending the time to talk about
    this topic here on your internet site.

  8. در جمع‌بندی نهایی

    برای اونایی که می‌خوان وارد بشن

    فعالیت‌های شرطی

    مشغولن

    این سرویس آنلاین

    مطمئناً می‌تونه

    کاربردی باشه

    از سوی دیگر

    پروژه‌هایی مثل

    وبسایت enfeјaгonline

    و

    sіbbet

    در حال رشد هستن

    به طور کلی

    خوب بود

    و

    به زودی

    بهش برمی‌گردم

    Нave a look at mуy weƅ-site :: رسانه علمی

  9. I really like your blog.. very nice colors & theme. Did you make this website
    yourself or did you hire someone to do it for
    you? Plz answer back as I’m looking to create my own blog and would like to find out
    where u got this from. thanks

  10. I’m not sure exactly why but this site is loading incredibly
    slow for me. Is anyone else having this issue or is it a issue on my end?
    I’ll check back later and see if the problem still exists.

  11. Внедрение с нуля для нового бизнеса — помогли выстроить учёт правильно с самого начала. Не пришлось потом переделывать как у тех кто начинал с Excel и хаоса. аудит 1С Белгород

  12. Спецтехника для государственного предприятия — специфические требования к документации и приёмке. Нашли решение под наши задачи всё оформили корректно по требованиям законодательства РК. ремонт спецтехники Алматы

  13. Hola! I’ve been reading your site for some time now and finally got
    the courage to go ahead and give you a shout out from Houston Tx!
    Just wanted to mention keep up the fantastic job!

  14. Compared to peptides manufactured by ribosomes, NRPs are more resistant to hydrolases and reveal raised
    stability in vivo.

  15. Ahaa, its fastidious conversation concerning this paragraph here at this
    weblog, I have read all that, so at this time me also commenting
    here.

  16. I needed to thank you for this very good read!! I definitely enjoyed every bit of it.
    I have got you book-marked to look at new stuff you post…

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>