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

  1. Добрый день Для конкурентных тематик важна связка из технической базы контента коммерческих факторов и понятного пользовательского пути. Такая логика особенно актуальна когда нужен сайт для бизнеса. Один из релевантных вариантов — продающий сайт для бизнеса: https://volt-site.ru/uslugi/seo-prodvizhenie Такой формат особенно полезен для ниш где клиент сравнивает несколько подрядчиков перед обращением. web разработка сайтов онлайн сайт под ключ услуги разработка сайта цена стоимость конверсионный сайт стоимость seo для сайта онлайн создание сайта цена онлайн Всего наилучшего и роста в топ

  2. Добрый день Если текущий сайт устарел медленно загружается или не конвертирует трафик в заявки точечных правок может быть недостаточно. Иногда эффективнее пересобрать структуру усилить тексты и сделать новый проект на чистой технической базе. Вариант решения — разработка сайтов под ключ: https://volt-site.ru/uslugi/razrabotka-sajtov Особенно важно заранее продумать какие страницы будут собирать коммерческий спрос. продвижение сайта премиум лендинг для привлечения заявок стоимость разработки сайта услуги seo для сайта сайт интернет магазина цена заказать сайт с гарантией Всего наилучшего и роста в топ

  3. Для тех, кто ищет информацию по теме “Последние новости и обзоры мира MMA”, нашел много полезного.

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

    https://mma-hype.ru

  4. Today, while I was at work, my cousin stole my iphone and tested
    to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views.
    I know this is entirely off topic but I had to share
    it with someone!

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>