Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
java
java
        // should generate a file also
        File file = new File("target/" + input.getIncidentId() + ".txt");
        assertTrue("File should exists", file.exists());

Smarter Unit Testing with Spring

The unit test above requires us to assemble the Camel pieces manually in java code. What if we would like our unit test to use our spring configuration file axis-example-context.xml where we already have setup the endpoint. And of course we would like to test using this configuration file as this is the real file we will use. Well hey presto the xml file is a spring ApplicationContext file and spring is able to load it, so we go the spring path for unit testing. First we add the spring-test jar to our maven dependency:

Code Block
xml
xml

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

And then we refactor our unit test to be a standard spring unit class. What we need to do is to extend AbstractJUnit38SpringContextTests instead of TestCase in our unit test. Since Spring 2.5 embraces annotations we will use one as well to instruct what our xml configuration file is located:

Code Block
java
java

@ContextConfiguration(locations = "classpath:axis-example-context.xml")

What we must remember to add is the classpath: prefix as our xml file is located in src/main/resources. If we omit the prefix then Spring will by default try to locate the xml file in the current package and that is org.apache.camel.example.axis. If the xml file is located outside the classpath you can use file: prefix instead. So with these two modifications we can get rid of all the setup and teardown code we had before and now we will test our real configuration.

The last change is to get hold of the producer template and now we can just refer to the bean id it has in the spring xml file:

Code Block
xml
xml

        <!-- producer template exposed with this id -->
        <camel:template id="camelTemplate"/>

So we get hold of it by just getting it from the spring ApplicationContext as all spring users is used to do:

Code Block
java
java

        // get a producer template from the the spring context
        ProducerTemplate template = (ProducerTemplate) applicationContext.getBean("camelTemplate");
        // inject it on our service using the setter
        service.setTemplate(template);

So using this

TODO: How to embed Jetty and run a unit test by hitting a webservice call and expect the file output
TODO: Spring use onInit() to get the service once
TODO: Use spring dependency injection instead of property
TODO: Use Camel annotations
TODO: Maybe a route?
TODO: Use Camel Test Kit
TODO: Refer to Axis documentation. AXIS -> Axis.
TODO: Add more links to Camel stuff
TODO: Link to other tutorials