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

  1. Особенно понравился материал про Как стриминги меняют музыкальную индустрию.

    Смотрите сами:

    https://dinoera.ru

  2. Não é lenda, o Forra Máxima do Dragon Hatch bateu pra mim nesse exato momento. Forra de R$ 12.000.

  3. По теме “Актуальные события и изменения в Липецкой области”, нашел много полезного.

    Смотрите сами:

    https://media48lip.ru

  4. Piggy Gold tá distribuindo Forra Máxima agora pouco. Peguei R$ 8.000 e já parei de jogar. Minha mão tá suando.

  5. Тур в Кемер для двоих — горы море и сосновые леса рядом. Менеджер порекомендовал курорт сам когда узнал что мы любим природу. Отличный выбор вернёмся обязательно. турагентство Турция Москва

  6. Hi there it’s me, I am also visiting this web site on a regular
    basis, this web page is in fact pleasant and the users are actually sharing good thoughts.

  7. Для тех, кто ищет информацию по теме “Тренды и инвестиции в экономике России”, есть отличная статья.

    Смотрите сами:

    https://rubl-journal.ru

  8. Доброго В нише локального бизнеса шаблонный дизайн часто не отражает специфику ниши поэтому структура и контент должны проектироваться индивидуально. Поэтому сайт для бизнеса лучше делать с опорой на аналитику семантику UX и понятную воронку заявки. Один из вариантов решения — сайт для бизнеса: https://volt-site.ru/kontakty создание лендинга для косметологии разработать сайт удаленно продвижение сайта на коде создание сайта цена студия SEO продвижение для заявок конверсионный сайт в москве Всего наилучшего и роста в топ

  9. 인상적인 공유입니다! 방금 이것을 직장 동료에게 전달했습니다.
    그가 이에 대해 약간 숙제를 하고
    있었거든요. 그리고 그는 실제로 저에게 아침을 사줬습니다, 왜냐하면 제가 그를 위해 이것을 발견했기 때문입니다…
    lol. 그래서 다시 말하자면… 식사에 감사합니다!!
    하지만, 이 이슈를 여기 당신의 사이트에서 논의하는 데 시간을 내줘서 감사합니다.

    Hey there, I think your website might be having
    browser compatibility issues. When I look at your website in Safari, it looks fine
    but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that,
    fantastic blog!

    Your blog is a breath of fresh air! The way you present
    ilukiri is both engaging and insightful. I’ve shared
    this with my network. Any plans to create video content to complement your posts?
    Thanks for the great work!

    정말 멋진 사이트입니다! 글쓰기 스타일이 너무 매력적이고, заказать газели에 대한 설명이 정말 명확해요.
    새로운 블로거를 위한 조언이 있다면 공유해 주세요.

    고맙습니다!

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>