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

  1. Доброго Легендарное российское качество и стиль на воде воплощает аренда Azimut Владивосток для тех кто ценит итальянский дизайн. Яхты этого бренда известны своими элегантными линиями инновационными планировками и высоким уровнем комфорта на борту. Вы сможете арендовать современное судно для прогулки по заливу рыбалки или проведения частного мероприятия с шиком. Опытная команда обеспечит безопасность и сервис соответствующий мировым стандартам яхтинга. Почувствуйте вкус настоящей морской роскоши на яхте Azimut в водах Японского моря. Полная информация по ссылке – https://aldita.ru/ Туристический портал Самара Аренда катамарана Пхукет Аренда Кроссовер Аренда Хонда Аренда яхты Владивосток Всего наилучшего и хорошей информации

  2. Доброго На доске объявлений вы найдете множество свежих объявлений о продаже недвижимости в Усть-Каменогорске. Объявления о продаже домов и квартир обновляются регулярно. Бесплатные объявления с фото и подробными описаниями помогут вам сделать правильный выбор. Подать объявление можно легко и быстро просто заполнив форму на сайте. Объявления Каменогорска помогут вам найти идеальное жилье. Полная информация по ссылке – https://natumbe.kz профиль металлический такси межгород астана игровая приставка ps5 xbox путевой лист оформление гель лак набор стартовый прицел оптический ночной Всего наилучшего и хорошей информации

  3. В этой публикации мы исследуем ключевые аспекты здоровья включая влияние образа жизни на благополучие. Читатели узнают о важности правильного питания физической активности и психического здоровья. Мы предоставим практические советы и рекомендации для поддержания здоровья и развития профилактических подходов. Открыть полностью – Наркологическая клиника «Похмельная служба» в Краснодаре

  4. There is something really appealing about the way this post presents its ideas since it keeps the reader interested from start to finish while also leaving enough room for people with different opinions to think about the topic and share their own perspective respectfully. no deposit bonus

  5. This post feels very balanced and easy to read because the ideas are presented in a clear way while still keeping the discussion enjoyable and enjoyable for different readers online. no deposit bonus

  6. Your ability to synthesize such a wide range of details into one clearly connected unbiased article is highly impressive. It takes real skill to present facts so clearly and I genuinely enjoyed reading through this well-organized material during my downtime earlier this afternoon. free spins no deposit

  7. I like how this post presents the ideas in a natural way that feels both meaningful and comfortable to read online. no deposit bonus

  8. One of the best things about this post is how easy to connect with and thoughtful the tone feels because it creates a more welcoming atmosphere for readers who want to engage with the discussion and share their own thoughts. free spins no deposit

  9. This post creates a good sense of structure between being useful and staying approachable since the wording feels clear the structure is well organized and the overall discussion encourages people to share different perspectives comfortably. no deposit bonus

  10. Доброго Огненные горы и гейзеры Камчатки ждут смельчаков выбирающих экскурсии Петропавловск-Камчатский для экстремального туризма. Вы увидите действующие вулканы искупаетесь в термальных источниках и понаблюдаете за медведями в естественной среде обитания. Вертолетные заброски позволяют добраться до самых удаленных уголков полуострова недоступных для наземного транспорта. Опытные гиды обеспечат безопасность в диких условиях и расскажут увлекательные истории о геологии и жизни края. Это путешествие для тех кто хочет увидеть край земли и почувствовать мощь природной стихии своими глазами. Полная информация по ссылке – https://aldita.ru/ Экскурсии Иркутск Услуги гида Аренда Кроссовер Владивосток Аренда квартиры Пхукет Аренда байка Всего наилучшего и хорошей информации

  11. I appreciate how this post creates a relaxed and thoughtful atmosphere for discussion since the tone feels friendly and open while the ideas themselves are presented clearly and in a well structured manner throughout. no deposit bonus

  12. This post creates a welcoming and interesting atmosphere by presenting the topic in a easy-to-understand and balanced way throughout. no deposit bonus

  13. I enjoy how this post keeps the discussion insightful and natural at the same time because it makes the overall content more enjoyable to read. no deposit bonus

  14. Thank you for putting together such a well-organized and perfectly neutral summary. The way you organized the facts allows the reader to follow along effortlessly without missing any key details here. no deposit bonus

  15. I like how this post keeps the discussion thoughtful and enjoyable while still maintaining a simple and accessible style because that combination makes the content easier to understand and more enjoyable for different readers online. no deposit bonus

  16. Thank you for taking the time to put this comprehensive overview together as it really helps clarify a lot of the questions I had regarding this topic and provides a solid foundation for further exploration. no deposit bonus

  17. I enjoy how this post combines simplicity and substance in a way that keeps the discussion engaging understandable and open enough for readers with different viewpoints to participate comfortably in the conversation. no deposit bonus

  18. I appreciate how the tone here stays easygoing and useful helping the discussion feel more smooth and comfortable overall. no deposit bonus

  19. This post creates a really well-rounded atmosphere for discussion because the tone remains positive and natural while the ideas themselves are presented clearly and in a way that feels relatable. free spins no deposit

  20. There is a really good flow throughout this post that keeps the discussion easy to understand and interesting to follow while also maintaining a calm tone that works well for a broad audience of different readers. free spins no deposit

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>