Joine Music

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 4 October 2012

Writing Unit Tests to Ensure Your "@Transactional ... rollbackFor" Annotations are Honoured

Posted on 04:50 by Unknown
Thanks to Russ Hart for providing the info on how to get this to work.  I just cut and paste, and then blogged it.

It's nice to write unit tests.  I wanted to write a set of tests for a method that I'd marked with the Spring @Transactional annotation:


          @Transactional(propagation = Propagation.MANDATORY, rollbackFor = {MessagingException.class})
    @Transformer
    public IncomingEmailDTO receiveMessage(Message message) throws MessagingException {

        IncomingEmailDTO emailDTO = null;
        ...

The tests for the method were simple. But then I realised I wanted to also test that rollbacks were happening or not as required as specified by the "rollbackFor = {MessagingException.class}" part of the annotation.

A quick aside (because I was asked this by the person who gave me the solution to this, and it's entirely valid).  Why did I want to test this?  Aren't I just testing that this Spring annotation works?  In part, yes, this will be the effect of any tests for this.  But there was something else I wanted.  Unit tests, over time, build into a massive, executable spec. for your system.  It would be very easy for someone in the future to change this small part of the annotation (or remove it altogether) and have a very significant effect on the running of the whole system.  Consequently, by adding tests which check that this test is a) transactional, and b) set to rollback for specific exceptions only; I can protect myself against this unfortunate outcome.

But back to the example.  

We had the following Spring XML config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
  
    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:MYSID"/>
        <property name="username" value="ME"/>
        <property name="password" value="ME"/>
    </bean>
</beans>
And then in our unit test we had to have the following:

@ContextConfiguration(locations = {"classpath:spring/appContext-incomingEmailReceiverTest.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class IncomingEmailTransformerTest {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Transactional
    @Test
    public void test_transform_valid_incoming_email_with_no_attachment_works_and_no_rollback()
            throws MessagingException {
    
        IncomingEmailDTO result = emailTransformer.receiveMessage(validInputMessage);

        assertFalse(transactionManager.getTransaction(null).isRollbackOnly());
    }

    @Transactional
    @Test
    public void test_MessagingException_when_extracting_originator_gets_thrown_and_tx_rolls_back()
            throws MessagingException {

        stub(mockEmailDataExtractor.extractOriginator(incomingEmailMessage)).toThrow(new MessagingException());
    
        IncomingEmailDTO result = emailTransformer.receiveMessage(validInputMessage);

        assertTrue(transactionManager.getTransaction(null).isRollbackOnly());
    }


And there we have it.
Read More
Posted in | No comments
Newer Posts Older Posts Home
Subscribe to: Comments (Atom)

Popular Posts

  • EJB 3.0 Outside the Container, Inside the JVM - Part 2: Configuring JPA Declaratively
    Welcome to part two of this blog entry introducing using EJB3.0 inside the JVM. Click here to view the first part. As we've seen, JPA ...
  • (no title)
    The Significance and Importance of Quotes in JSTL EL I just spent a few hours debuggung a null pointer in a Portlet JSP I'm writing. It...
  • Project Wonderland BOF (BOF-1306) @ JavaOne 2007
    These are my notes which I took during the Project Wonderland BOF at JavaOne 2007. Enjoy. Paul Byrne - Lead of Wonderland What is project w...
  • Maven 1.0.2: Adding a resource to a jar
    Want to add a resource such as an xml config file to your generated jar in Maven 1.0.2? Create a directory called ./resources in the base di...
  • EJB 3.0: One Model Inside and Out (Pt. 2) - The POJO Model Itself – Annotations and Relationships
    Please note, this blog entry is based heavily on many other things out there on the web at the moment, most particularly this tutorial on ne...
  • (no title)
    List Insert Based on CompareTo Here's some code I've had to write more than once. It inserts something into a list at a position ba...
  • Project Acta Diurna - Harnessing RSS Goodness for Project Glory
    Last week I was bitten three times in quick succession by a lack of knowledge about what was going on around me in the rest of the team. On ...
  • Booting Apache Derby ("JavaDB") with your Java App's Startup
    If you're embedding the Derby RDBMS with your java desktop application and want it to start when you start your app, you need to make th...
  • EJB3: Listing the Complete Contents of a Table
    It took me a while to work this out. Here is is for posterity: String queryString = "SELECT r FROM Recipe r WHERE r.id > 0"; Q...
  • Note to Self: Windows Pathnames in Java
    This gets me every time. I had to specify a jvm option in a maven properties file. It took ages, due to spaces in the path name. This wor...

Categories

  • 0
  • 2008
  • ant maven pimp build javaone 2008
  • apple ipod touch
  • asm
  • blog new ruby
  • blogtag list
  • bond casinoroyale mashup mi6 film movie
  • build
  • bytecode
  • CI
  • cobertura
  • communityone 2008 nutter jvm scala jruby groovy davinci
  • communityone 2008 opensocial socialsite
  • communityone javaone keynote oreilly
  • configuration
  • cowley
  • css div layout column ie firefox safari example
  • custom
  • darkstar mpk20 wonderland java3d commaboration SL
  • dashboard rss communication news development
  • db2 database SQL max min howto tip
  • db2 database ibm lessons tips
  • db2 database load batch howto example
  • db2 import upload data howto command
  • debt technical java annotation
  • debugging tips javaone 2008
  • development web2.0
  • findbugs JavaOne 2008 pugh
  • findbugs JavaOne BOF notes
  • gafter closures java javaone notes
  • google trouble patriarchal patriarchy
  • groovy metaprogramming javaone 2008
  • grubby oss data generation project announce
  • guice javaone 2008
  • gwt maven howto example simple
  • howto
  • hudson
  • hudson CI javaone 2008
  • ibm
  • invokeDynamic jvm dynamic ruby javaone
  • itinerant web2.0 portable desktop
  • jacl was websphere wsadmin trace logging
  • james gosling sun java open source tech days second life SL
  • jar java manifest properties config howto tip
  • java
  • java applet javaone 2008 reloaded jnlp
  • java javafxscript javaone 2008 fxscript
  • java javaone 2007 07
  • java javaone 2008 bytecode cobertura asm singleton testability
  • javaone
  • javaone keynote gage schwarz javafx
  • javaone semantic web bof notes web3
  • jazz
  • jruby rails javaone charlesnutter thomasenebo
  • jruby ruby netbeans development
  • kill dead laptop computer rebuild restore
  • lessonslearned
  • mac osx java gui shellscript classpath problem solution
  • maven plugin unittest test packager
  • mylin mylar javaone eclipse 2008
  • netbeans development ide
  • netbeans development ide RC
  • netbeans maven2 profiling
  • netbeans ruby sun tech days visual web pack roman strobl
  • ola bini java javaone 2008 thoughtworks ruby jruby
  • openjdk java javaone javafx wonderland
  • overheard
  • pojo ejb3.0 jpa orm java example howto
  • rant
  • rest restful jsr311 java web2.0 javaone ts-6411
  • rome rss feed blog rss atom propono java javaone
  • rsa uml profile plugin howto
  • ruby inheritance example
  • ruby jruby rss xml hpricot
  • ruby unless example
  • scm
  • setup
  • subversion svn xp windows cleanup
  • sun java soa web2.0 netbeans opensource javacaps
  • sun tech days java derby database rdbms london
  • sun tech days london impressions
  • terracotta java javaone 2008 android gwt
  • tip
  • tips
  • vwp netbeans JPA howto
  • was jython scripting nfr ibm pmi jvm
  • was tpv jython scripting nfr ibm pmi
  • webrick ruby jruby actadiurna investigation code howto
  • workitem

Blog Archive

  • ▼  2012 (1)
    • ▼  October (1)
      • Writing Unit Tests to Ensure Your "@Transactional ...
  • ►  2010 (8)
    • ►  November (1)
    • ►  October (3)
    • ►  June (1)
    • ►  May (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2009 (9)
    • ►  December (1)
    • ►  November (5)
    • ►  March (2)
    • ►  February (1)
  • ►  2008 (22)
    • ►  December (1)
    • ►  November (3)
    • ►  May (15)
    • ►  March (1)
    • ►  January (2)
  • ►  2007 (53)
    • ►  December (1)
    • ►  November (3)
    • ►  September (3)
    • ►  August (2)
    • ►  July (3)
    • ►  June (1)
    • ►  May (12)
    • ►  April (5)
    • ►  March (13)
    • ►  February (7)
    • ►  January (3)
  • ►  2006 (35)
    • ►  December (8)
    • ►  October (1)
    • ►  August (1)
    • ►  July (5)
    • ►  June (8)
    • ►  May (3)
    • ►  April (7)
    • ►  March (2)
Powered by Blogger.

About Me

Unknown
View my complete profile