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,274 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. I have been browsing online more than three hours nowadays, yet I
    never found any attention-grabbing article like yours.
    It is pretty value sufficient for me. In my view, if all webmasters
    and bloggers made just right content material as you probably did,
    the net will likely be much more helpful than ever before.

  2. Хотите смотреть сериалов бесплатно? нашёл хорошую подборку Кино – это источник вдохновения для многих творческих людей. Оно может подарить новые идеи мотивировать на действия и помочь переосмыслить взгляд на мир. все фильмы Смотреть фильмы онлайн – это не просто досуг это инвестиция в ваше развитие. Найдите свой источник вдохновения. Заходите сюда: — https://www.filmy-serialy-online-1.top смотреть кино бесплатно и онлайнонлайн кино без регистрациикино онлайн без регистрации Надеюсь вы оцените

  3. An interesting discussion is definitely worth comment. I do believe
    that you ought to publish more on this subject matter, it might not be a taboo
    matter but typically people do not talk about such issues. To the next!
    Cheers!!

  4. Excellent post! I truly like how you explained the importance of working with a professional Web development agency to establish a strong digital presence.
    In today’s competitive market, combining website optimization with a reliable Seo agency strategy is essential for sustainable growth.

    From my experience, having an experienced Web Developer and Software Developer team makes a huge difference in terms
    of scalability and long-term performance. Solutions such
    as wordpress web development and Custom Software Development can significantly enhance operational efficiency when implemented properly.

    ERP System integration, especially in projects like Odoo Malaysia, is becoming increasingly important for
    businesses looking to simplify accounting, HR, sales, and inventory processes.

    Thanks for posting these valuable insights — looking forward
    to more updates!

  5. Hi there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Ie.
    I’m not sure if this is a format issue or something to do
    with internet browser compatibility but I thought I’d
    post to let you know. The style and design look great though!
    Hope you get the problem fixed soon. Kudos

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

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

  7. I have read so many articles regarding the blogger lovers
    except this piece of writing is really a nice article, keep it up.

  8. I know this web page offers quality depending articles or reviews and other stuff,
    is there any other web page which offers these data in quality?

  9. excellent submit, very informative. I’m wondering
    why the opposite experts of this sector don’t understand this.
    You should proceed your writing. I am confident, you’ve a great readers’ base already!

  10. Everyone loves what you guys tend to be up too. Such clever work and coverage!
    Keep up the wonderful works guys I’ve incorporated you guys to
    my own blogroll.

  11. Good day! I know this is kind of off topic
    but I was wondering which blog platform are you using
    for this site? I’m getting fed up of WordPress because I’ve had issues with
    hackers and I’m looking at options for another platform.
    I would be fantastic if you could point me in the direction of a good platform.

  12. Link exchange is nothing else but it is only placing the other person’s web
    site link on your page at appropriate place and other person will also do same in support of you.

  13. In 2026, WhatsApp marketing at scale demands more than raw
    accounts — it requires whatsapp hash channels.
    These specially formatted sessions let automation tools send
    bulk messages without QR code logins, dramatically reducing detection risks.
    The whatsapp wart extractor is the industry-standard whatsapp hash channel
    creator that converts any WhatsApp account into ready-to-use hash channels
    in seconds.
    This guide explains everything: the whatsapp hash channel
    6 segment format, step-by-step conversion, how to buy whatsapp hash channels safely,
    and proven whatsapp hash channels anti ban tactics that keep accounts
    alive for months.

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

    در کل قضیه

    برای علاقه‌مندان به

    بازی‌های جایزه‌دار

    دنبال تجربه هستن

    این سرویس

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

    مفید باشه

    جالبه که

    نام‌هایی مثل

    enfejar օnline

    و

    برند siƅbet

    حضور پررنگی دارن

    در کل داستان

    دلنشین بود

    و

    در ادامه

    بازم میام

    .

    Here is mmy websitte سایت خبری دولتی

  15. This article is in fact a pleasant one it assists
    new the web people, who are wishing for blogging.

  16. You could definitely see your skills within the work you write.
    The arena hopes for more passionate writers such as you who are not afraid to
    say how they believe. At all times follow your heart.

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>