Monthly Archives: September 2012

JUnit testing with Spring Webflow

Spring Webflow sample

I love SpringSource related technologies because of the supporting classes they provide for Test Driven Development (TDD). I do TDD for 2 reasons,

  • I design the objects using spring webflow application from nothing, writing the tests first and evolving the code efficiently to support the tests and making the test success and finally the building the application
  • In the process, I am building a regression testing framework, a “safety net”. The advantage of this is when we change the backend, I always make sure the tests I have build will surely succeed and in the process the design matures

All the spring frameworks Spring WebFlow being no exception do a good job of this. In this blog I will show you how I do TDD for a simple Spring WebFlow. Those who are new to Spring WebFlow, it is a framework that support data/session management between pages, when you navigate in a workflow within a user session. For example, in the below example, I will talk about the hotel booking application where there is a submit booking, proceed/confirm or cancel booking(2 step webflow). Spring WebFlow helps in managing the session between these 2 steps (pages) without you worrying about session/request data management.

Luckily someone has already built this simple hotel booking application. The way I would build this application is, I will start off with a test as below,

public class BookingFlowExecutionTests extends AbstractXmlFlowExecutionTests {

private BookingService bookingService;

protected void setUp() {
bookingService = EasyMock.createMock(BookingService.class);

protected FlowDefinitionResource getResource(
FlowDefinitionResourceFactory resourceFactory) {
return resourceFactory

protected void configureFlowBuilderContext(
MockFlowBuilderContext builderContext) {
builderContext.registerBean("bookingService", bookingService);

public void testStartBookingFlow() {
Booking booking = createTestBooking();

EasyMock.expect(bookingService.createBooking(1L, "keith")).andReturn(


MutableAttributeMap input = new LocalAttributeMap();
input.put("hotelId", "1");
MockExternalContext context = new MockExternalContext();
startFlow(input, context);

assertResponseWrittenEquals("enterBookingDetails", context);
assertTrue(getRequiredFlowAttribute("booking") instanceof Booking);


public void testEnterBookingDetails_Proceed() {
getFlowScope().put("booking", createTestBooking());

MockExternalContext context = new MockExternalContext();

assertResponseWrittenEquals("reviewBooking", context);

public void testReviewBooking_Confirm() {
getFlowScope().put("booking", createTestBooking());
MockExternalContext context = new MockExternalContext();

private Booking createTestBooking() {
Hotel hotel = new Hotel();
hotel.setName("Jameson Inn");
User user = new User("keith", "pass", "Keith Donald");
Booking booking = new Booking(hotel, user);
return booking;

AbstractXmlFlowExecutionTests is an interesting class as a part of spring-webflow.jar which provides all the plumbing for testing the flow and asserting the next steps within a spring webflow. Every test method that tests the flow will start with a “testXXX” method name. To begin with, there are no flow configuration file “src/main/webapp/WEB-INF/hotels/booking/booking-flow.xml”. The test will obviously will fail. As a first step, we need to define the spring flow as below,

<view-state id="enterBookingDetails" model="booking">
<binding property="checkinDate" />
<binding property="checkoutDate" />
<binding property="beds" />
<binding property="smoking" />
<binding property="creditCard" />
<binding property="creditCardName" />
<binding property="creditCardExpiryMonth" />
<binding property="creditCardExpiryYear" />
<binding property="amenities" />
<render fragments="body" />
<transition on="proceed" to="reviewBooking" />
<transition on="cancel" to="cancel" bind="false" />

<view-state id="reviewBooking" model="booking">
<render fragments="body" />
<transition on="confirm" to="bookingConfirmed">
<evaluate expression="bookingService.persistBooking(booking)" />
<transition on="revise" to="enterBookingDetails" />
<transition on="cancel" to="cancel" />

<end-state id="bookingConfirmed"/>

<end-state id="cancel" />

Once you add this configuration in “src/main/webapp/WEB-INF/hotels/booking/booking-flow.xml” file, and run the test again, the test will succeed.

If you notice carefully, transition on=”confirm” will call the business logic on the service layer, in this example, it will call “bookingService.persistBooking(booking)” business logic.

You also see that there are different controller methods like, enterBookingDetails and reviewBooking. These are associated with different view jsp file. But right now they are mocked and we just assert the controllers as in setCurrentState(“enterBookingDetailsreviewBooking”); and assertCurrentStateEquals(“enterBookingDetailsreviewBooking”); in JUnit test.

Now if we have to build views, we will have 2 views jsps, and configure them in view.xml as below,

<definition name="enterBookingDetails" extends="standardLayout">
<put-attribute name="body" value="/WEB-INF/hotels/booking/enterBookingDetails.jsp"/>

<definition name="reviewBooking" extends="standardLayout">
<put-attribute name="body" value="/WEB-INF/hotels/booking/reviewBooking.jsp" />

You can see the jsp pages in the location as mentioned above, but in the JSP file the key thing that contribute to the webflow is adding,

<form:form modelAttribute="booking" action="${flowExecutionUrl}">

The flowExecutionUrl spring webflow expression language variable will control the flow to next page. There are several such variable within Spring Webflow, for more details click here.

If you want to run this example, you just need to do

mvn tomcat:run

Other References:


JUnit testing with Spring Integration and Spring WS

Spring Integration, Spring WS for Webservice is a decent framework to design and implement Webservice. More than that it has a good JUnit testing support. In this section I will be talking about how we do implement a Webservice using Test Driven Development (TDD). The working sample is here in the Github .

As a first step we need to define the XSD schema:

<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="" xmlns:data="" xmlns:msg="" xmlns:svc="" targetNamespace="" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0">  <xsd:import namespace="http : //" schemaLocation="TestTransactions_v1.xsd"/>
<xsd:element name="TestServiceRequest" type="data:TestServiceRequestType"/>
<xsd:element name="TestServiceResponse" type="data:TestServiceResponseType"/>

<?xml version="1.0" encoding="UTF-8"?><xsd:schema xmlns:xsd="" xmlns:data="" xmlns:msg="" targetNamespace="" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xsd:complexType name="TestServiceRequestType">
<xsd:element name="Document">
<xsd:element name="Id" type="xsd:string" minOccurs="0"/>
<xsd:element name="Type" type="xsd:string" minOccurs="0"/>
<xsd:complexType name="TestServiceResponseType">
<xsd:element name="Document">
<xsd:element name="Result" type="xsd:string" minOccurs="0"/>

Writing the JUnit test as below,

public class TestIntegrationEndPointTest {

private ApplicationContext applicationContext;

private MockWebServiceClient mockClient;

public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);

public void testWsEndPointTest() throws Exception {
Source requestPayload = new StringSource("<?xml version=\"1.0\" encoding=\"UTF-8\"?><v1:TestServiceRequest xmlns:v1=\"\" xmlns:v11=\"\"><v11:Document><v11:Id>101</v11:Id><v11:Type>MaterialMaster</v11:Type></v11:Document></v1:TestServiceRequest>");
Source responsePayload = new StringSource("<testServiceResponseType xmlns=\"\" xmlns:ns2=\"\"><Document><Result>SUCCESS</Result></Document></testServiceResponseType>");


Now the test will still fail with need for Spring autowiring, the spring bean definition configuration for Spring WS looks as below,

<property name="endpointMap">
<entry key="{}TestServiceRequest" value-ref="TestBatchEndpoint" />
<int-ws:inbound-gateway id="TestBatchEndpoint" reply-channel="test.batch.webservice.out" request-channel="" />
<bean id="marshaller" >
<property name="contextPath" value="" />
<bean id="testServiceActivator" class=""/>
<bean id="resultTransformer" class="org.springframework.integration.xml.transformer.ResultToStringTransformer"/>

Spring Integration and Spring WS flow looks as below

<int:bridge  input-channel="" output-channel=""></int:bridge>
<int-xml:unmarshalling-transformer id="defaultUnmarshaller" input-channel="" output-channel="test.batch.webservice.unmarshalling.out" unmarshaller="marshaller"/>
<int:service-activator id="test.batch.webservice.activator" input-channel="test.batch.webservice.unmarshalling.out" ref="testServiceActivator" output-channel="">
<int-xml:marshalling-transformer input-channel="" output-channel="test.batch.webservice.out" marshaller="marshaller" result-transformer="resultTransformer" />

IBatisTemplate looks as below,

<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">>
<property name="sqlMapClient" ref="sqlMapClient" />

You need to create the Java stubs from the XSL for that you need to run,

mvn jaxb2:xjc

It assumes that you have XSDs at location src/main/xsd location by default, refer this article for more details.

In the Test class, you need to add the Spring JUnit testing capabilities as follows,

"classpath:config/test-webservice-beans-config-test.xml" })
public class TestIntegrationEndPointTest {

TestServiceActivator looks somewhat as below:

public class TestServiceActivator {
private static Logger logger = Logger.getLogger(TestServiceActivator.class);

SqlMapClientTemplate ibatisTemplate;

public TestServiceResponseType processRequest(JAXBElement element)    throws Exception {
TestServiceRequestType request = (TestServiceRequestType) element.getValue();
String status = "SUCCESS";
String type = request.getDocument().getType();
String id = request.getDocument().getId();

TestObject notifyObject = new TestObject();
ibatisTemplate.insert("testInsert", notifyObject);

TestServiceResponseType response = new TestServiceResponseType();

Document doc = new Document();

logger.debug("Successfully saved request");

return response;

One hack we need to do is, we need to add @XmlRootElement to the stubs that were created as per this article

@XmlType(name = "TestServiceResponseType", propOrder = {
public class TestServiceResponseType {

@XmlType(name = "TestServiceRequestType", propOrder = {
public class TestServiceRequestType {

Once you do this, we can run the mvn test and it will work. If you notice in this example, we have tested the String WS end to end using JUnit and Spring Integraiton.

For further reading refer .