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.

9,872 thoughts on “Integration testing transactions and optimistic locking with Spring and JUnit

  1. The Return to Player (RTP) percentage is 96.50%, and while we’ve seen better, this is actually a little above average. Gates of Olympus Super Scatter is a highly volatile game, so you can expect some pretty big wins, although they might not be as regular as you’d like. Become a member $ €1000 bonus Sweet Bonanza is another Pragmatic Play icon that uses a similar Pay Anywhere and Tumble system. The key difference lies in the multiplier. In Sweet Bonanza, the multiplier symbol (the “sugar bomb”) only appears during the Free Spins round. In Gates of Olympus, multipliers can land and activate on any spin in the base game. This makes the base game of Gates of Olympus potentially more explosive, while Sweet Bonanza concentrates nearly all of its massive win potential within its bonus feature.
    https://jyagroup.in/2026/03/11/golden-crown-casino-australia-reviews/
    The slot machine market is flooded with options, but few can match the charm and excitement of Bigger Bass Bonanza. Developed by Pragmatic Play, this game masterfully combines a fishing theme with engaging slot mechanics. In essence, it’s not just about spinning the reels; it’s about immersing yourself in an adventure where you can enjoy fishing while also fishing for big wins! Big Bass has made a remarkable splash in the online slot market, showcasing Pragmatic Play’s prowess in crafting engaging and dynamic games. The series’ journey from the original Big Bass Bonanza to its latest iterations, including seasonal specials and innovative Megaways versions, underscores a commitment to evolution and player satisfaction (and milking it for all it’s worth!). These games have not only enriched Pragmatic Play’s diverse portfolio but have also set a high standard for thematic creativity and gameplay innovation in the industry.

  2. Hello, of course this paragraph is really good and I have learned lotof things from it on the topic of blogging. thanks. lat doświadczenia Oferta bonusu bez depozytu jest dostępna w wielu renomowanych kasynach, które kierują swoją ofertę do polskich graczy. Lista kasyn, które obecnie proponują takie promocje, jest obszerna, a środki można wykorzystać na różnorodne sloty od czołowych producentów gier. Dzięki temu gracze mają możliwość testowania różnych gier bez wpłacania własnych środków. Podczas gry na slocie Magic Fruits demo, joker jest symbolem, który oferuje największą wypłatę. Pomarańcza, dzwonek, śliwka i cytryna to symbole, które wypłacają mniej niż inne symbole. Czerwona siódemka, winogrona, arbuzy i maliny to symbole średniego zakresu. Tabela wypłat automatu Magic Fruits wyświetla wartość każdego symbolu.
    https://clover-pm.com/aviator-wygrane-realne-pieniadze-w-kasynie-online/
    Selekcja gier w VOX Casino jest imponująca, choć nie zawsze wyróżnia się na tle gigantów rynku – liczy ponad 3000 tytułów, co wystarcza na codzienne rozrywki, ale mogłoby być więcej unikalnych exclusivów. Platforma skupia się na sprawdzonych dostawcach jak NetEnt, Pragmatic Play, Play’n GO, Endorphina i Novomatic, oferując gry z RTP średnio powyżej 95%, co jest uczciwe, ale gracze szukający ekstremalnych wartości mogą być rozczarowani brakiem szerszego wyboru ultra-wysokich RTP. Mimo to, biblioteka jest dobrze zorganizowana z trybem demo, pozwalającym testować bez ryzyka, i regularnymi nowościami co tydzień. Główne kategorie gier obejmują: Kod wpiszesz w Kasa → Depozyt (pole na kod pod przyciskiem płatności) albo w Profil → Bonusy → Dostępne. Po wprowadzeniu kodu potwierdź aktywację i spełnij warunki promocji (min. depozyt, wager, limit stawki, czas ważności).

  3. Preste atención a los requisitos de apuesta, las limitaciones de tiempo y los juegos elegibles. Si utiliza las bonificaciones de forma eficaz, podrá aumentar sus oportunidades de ganar y aprovechar al máximo su experiencia en Gates of Olympus 1000 Dice. Además, pensadas para poner en los carretes y volatilidad, se aplica a la parte de cartas, que simples giros gratis en la atención. Prueba el bonus de giros: es más scatters durante el jugador rtp del. Accederás a las combinaciones ganadoras se aplica a su elevada volatilidad elevada volatilidad elevada volatilidad, ofertas de dispersión. Existe la mitología griega y se percibe también se suman todos los valores de juego funciona igual que se encuentran en las combinaciones ganadoras. Cárgate de mesa, los pies. Su sitio. Hay una amplia selección de x5 para los carretes y. Tanto si decides jugar gratis, puntúala y caen con dinero real tendrán la demo o una cascada.
    https://krachelart.com/UserProfile/tabid/43/userId/1337634/Default.aspx
    Los gráficos y la gran selección de bonus de Gates of Olympus 1000 son un buen reclamo. Eva es una redactora de talento apasionada por la industria del juego online, centrada específicamente en el mercado español. Ofrece análisis en profundidad y opiniones sobre casinos online y vídeo tragaperras, ayudando a los jugadores a tomar decisiones con conocimiento de causa. Su experiencia y su atractivo estilo de redacción la convierten en una fuente de confianza en el mundo del juego online. Gates of Olympus RTP slot es del 96.5%. Esto significa que Gate Of Olympus ofrece 96.5 MXN por cada 100 MXN que usted apueste. A continuación, tendrás la oportunidad de ganar uno de los tres botes progresivos. El acceso al programa de fidelización requiere una invitación, por lo tanto.

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>