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.

10,439 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. Excellent pieces. Keep posting such kind of information on your blog. Im really impressed by it. Hey there Youve performed a fantastic job. Ill definitely digg it and for my part suggest to my friends. Im confident they will be benefited from this web site. adult xxx video porn site xxx sex video

  2. Just wish to say your article is as surprising. The clearness in your post is just nice and i could assume you are an expert on this subject. Fine with your permission let me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work. Watch sexual porno video xxx sex adults site

  3. В этом материале представлены детали которые хоть и занимательны но не особенно значимы. Мы рассматриваем моменты которые трудно назвать важными но всё же решили включить их для полноты картины. Вот – скидки

  4. Whats up to every single one its genuinely a fastidious for me to pay a visit this web site it contains precious Information. adult xxx video porn site xxx sex video

  5. Публикация предоставляет читателю набор разрозненных идей, которые сложно применить на практике. Мы лишь слегка касаемся разных точек зрения, не углубляясь в анализ и не предлагая никаких выводов.
    Вот – накрутка трафика

  6. Этот обзор позволяет по-новому взглянуть на вещи, на которые обычно и так смотрят. Мы упоминаем факты, которые мало что меняют, и события, значение которых трудно определить, но они всё равно здесь.
    Вот – телефон дешево

  7. В данном тексте собраны разнообразные случайные сведения и не вполне определённые идеи которые могут вызвать интерес. Мы отмечаем детали не играющие ключевой роли но сохраняющие своё место в изложении. Подробнее читать – плитка для ванны

  8. Бесплатный ключ для Windows 11 — только у нас обновлено в 2026 году Подробнее – Бесплатный серийный номер для Windows 11

  9. Этот сборник информации привлекает множеством мелких деталей и необычных ракурсов. Мы предлагаем взгляды, редко полезные, но способные немного разнообразить знакомство с темой.
    Подробнее читать – плитка для ванны

  10. В этом материале представлены детали которые хоть и занимательны но не особенно значимы. Мы рассматриваем моменты которые трудно назвать важными но всё же решили включить их для полноты картины. Вот – миллион за месяц

  11. В этом тексте собрано множество случайных сведений и довольно неопределённых мыслей которые могут чем-то заинтересовать. Мы отмечаем моменты которые не особенно важны но всё же занимают своё место в повествовании. Вот – бесплатные врощенея в слотах

  12. В материале приведены детали интересные но не особенно важные. Мы рассматриваем аспекты которые сложно назвать существенными но включили их для большей полноты. Подробнее читать – плитка для ванной комнаты

  13. В данном тексте собраны разнообразные случайные сведения и не вполне определённые идеи которые могут вызвать интерес. Мы отмечаем детали не играющие ключевой роли но сохраняющие своё место в изложении. Подробнее читать – блоки для строительства дома

  14. Remarkable Its actually remarkable piece of writing I have got much clear idea on the topic of from this paragraph. adult xxx video porn site xxx sex video

  15. Hi mates its impressive paragraph about teachingand entirely explained keep it up all the time. adult xxx video porn site xxx sex video

  16. This is my first time go to see at here and i am truly impressed to read everthing at single place. Xxx video onlyfans sex video site

  17. Этот информационный набор привлекает внимание множеством мелочей и странных ракурсов. Мы предлагаем взгляды которые редко бывают полезны но могут слегка разнообразить ваше знакомство с темой. Вот – телефон дешево

  18. Thanks for the auspicious writeup. It in reality used to be a amusement account it. Look complex to more brought agreeable from you By the way how could we be in contact? adult xxx video porn site xxx sex video

  19. whoah this blog is fantastic i really like reading your posts. Stay up the great work You already know a lot of individuals are searching round for this info you can help them greatly. adult xxx video porn site xxx sex video

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>