Thursday, September 11, 2008

Partial mocking of objects using easymock classextensions

Ocassionally, some of your methods in your classes need to call some other public methods in the same class to get the job done. But when writing unit tests for the calling methods, you want to keep your tests isolated from the calls to other public methods. I encountered such a scenario recently and found that Easymock can help you by mocking some of the methods while keeping the rest of the methods intact.

Let us see an example,
The BlogSearchService has two public methods, first method filterBlogsByAuthor takes an author name and a list of blogs and returns all the blogs written by that particular order author.
The other business method searchBlogs will take a search paramter and the author, it will get all the blogs by the search parameter using a custom logic and do some other house keeping tasks like sorting them by published date and number of comments and then filter the methods by author.

package com.teja.blogs;

import java.util.Collections;
import java.util.List;

* @author Teja

public class BlogSearchService {

public List<Blog> searchBlogs(String searchString, String author){

//do some custom logic here on these blogs like sorting them by posted date.
return filterBlogsByAuthor(author, Collections.EMPTY_LIST);

public List<Blog> filterBlogsByAuthor(String author, List<Blog> blogs){
return Collections.EMPTY_LIST;


When writing the test cases for the second method, I don't want to test the other public method filterByAuthor as
(i)it has already been tested by other test cases,
(ii)I want to keep my test cases more unit.

So in my test case where I am testing my searchBlogs, I am creating the mock service class which has mock methods only for filterBlogsByAuthor, but the actual mehtod(searchBlogs) which is about to be tested is not.
As usual you can do expectations on the mock class, replay and verify as if it is some other external resource being mocked.

To create a partial mock class of the service, the extra parameter you need to pass is the name of the method to be mocked and the parameter types it accepts (coz, it need to know which version of the method you want to mock if you have overloaded methods)

Here is our test class:

package com.teja.blogs;

import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.easymock.classextension.EasyMock;

* @author Teja

public class BlogSearchServiceTest {

public void testSearchBlogs() throws NoSuchMethodException {
String author = "Teja";
BlogSearchService blogSearchService =EasyMock.createMock(BlogSearchService.class,
BlogSearchService.class.getMethod("filterBlogsByAuthor", new Class[]{String.class, List.class}));
EasyMock.expect(blogSearchService.filterBlogsByAuthor(author, Collections.EMPTY_LIST)).andReturn(Collections.EMPTY_LIST);
blogSearchService.searchBlogs("easymock", author);


Saturday, September 6, 2008

Pagination in rails using will_paginate

Pagination is a technique of presenting large amount of data on the UI, allowing the users to navigate between pages/data in an easy way.
Being a java developer for so many years, I remember doing dirty logic to achieve pagination to using some very useful and advanced tag libraries like displaytag. What ever may be the technique, pagination is never been an easy task.
But when I started playing around with rails and I got a situation where I need to do some pagination. And I readily found a gem will_paginate and doing pagination on rails is a breeze.

Lets get started first by installing the gem.

sudo gem install will_paginate

To check whether the plugin installed successfully or not, you can do the following in your rails console.

defined? WillPaginate
ActiveRecord::Base.respond_to? :paginate

Now lets add pagination support to an imaginary page listing all the clients

  def list_clients
@clients = Client.paginate(:page => params[:page], :per_page => 5)
and then render the pagination in the ui using this simple snippet


<%= will_paginate @clients %>
<!--Loop through all the clients and printem-->
<table width=100% cellpadding=0 cellspacing=0 border=0>
<% for @client in @clients do%>
<tr class='client_details'>
<td align='center'><%=@client.client_name.upcase%><
<%=@client.address_line_1%>,<%=@client.address_line_2%><br />

The code <%= will_paginate @clients %> will add the links to previous/next page along with the page numbers to naviage.
The next few lines of code is just to print the client details.

Monday, August 25, 2008

Developing web services using Spring ws and JAXB marshaller

Spring web services a product of spring community, helps in developing web services using contract first web services and helps in manipulating the xml in many ways. In this tutorial I am about to show a step by step guide in developing spring web services using JAXB as mashalling technology.

You can download spring, spring web services here.

We are about to develop a web service which search the blogs based on a search criteria on title string and published date.

So lets get started,

1.Create a web application
This is a general spring web MVC application. for a skeleton application, you can just run this maven archetype to quickly start with,

mvn archetype:create \
-DarchetypeArtifactId=spring-ws-archetype \
-DarchetypeVersion=1.5.4 \
-DgroupId=com.teja \

Or you can just add the spring nature to your existing web application by configuring the web.xml shown in the next step. Here is the file structure I am using for this simple demo.

2.Configure web.xml.
  1. <servlet>

  2. <servlet-name>spring-ws</servlet-name>

  3. <servlet-class></servlet-class>

  4. </servlet>

  5. <servlet-mapping>

  6. <servlet-name>spring-ws</servlet-name>

  7. <url-pattern>/*</url-pattern>

  8. </servlet-mapping>

  9. <servlet-mapping>

  10. <servlet-name>spring-ws</servlet-name>

  11. <url-pattern>*.wsdl</url-pattern>

  12. </servlet-mapping>

  13. <servlet-mapping>

  14. <servlet-name>spring-ws</servlet-name>

  15. <url-pattern>*.soap</url-pattern>

  16. </servlet-mapping>

Spring strongly supports only contract first web services for several reasons like Fragility, performance, re usability and versioning.
You can find more information visit this link

So lets start first by developing our XSD....
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <xsd:schema xmlns:xsd=""

  3. targetNamespace="http://com.tejakantamneni/schemas"

  4. xmlns:tns="http://com.tejakantamneni/schemas"

  5. elementFormDefault="qualified">

  6. </xsd:schema>

This is a plain regular xsd where we will define all our xml elements going to create our wsdl file.
Lets define our blog object, the blog is just a complex type object with three properties the "Title" for the blog, the "AbstractDetail" of the blog and the date when the blog is published "PublishedDate". This can be defined in the xml complex type
as follows...

  1. <xsd:complexType name="Blog">

  2. <xsd:sequence>

  3. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  4. <xsd:element name="AbstractDetail" type="xsd:string" nillable="true"/>

  5. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  6. </xsd:sequence>

  7. </xsd:complexType>

Next step is defining the search criteria object, I am wrapping the search criteria into a seperate object so that in future, we can extend the search criteria by adding more elements like author, subject. Here the xsd definition of the search criteria
object with two fields title and published date.

  1. <xsd:element name="SearchCriteria">

  2. <xsd:complexType>

  3. <xsd:sequence>

  4. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  5. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  6. </xsd:sequence>

  7. </xsd:complexType>

  8. </xsd:element>

The next stepa are creating the actual request object for our web service, which is basically a wrapper on the search criteria and our response object which is just a array/list of blog objects (which can be either zero size, if search results nothing
or can be of size n if search returns n objects).
Here is our completed xsd,
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <xsd:schema xmlns:xsd=""

  3. targetNamespace="http://com.tejakantamneni/schemas"

  4. xmlns:tns="http://com.tejakantamneni/schemas"

  5. elementFormDefault="qualified">

  6. <xsd:element name="BlogSearchRequest">

  7. <xsd:complexType>

  8. <xsd:sequence>

  9. <xsd:element ref="tns:SearchCriteria" minOccurs="0" maxOccurs = "unbounded" />

  10. </xsd:sequence>

  11. </xsd:complexType>

  12. </xsd:element>

  13. <xsd:element name="BlogSearchResponse">

  14. <xsd:complexType>

  15. <xsd:sequence>

  16. <xsd:element name="blogList" type="tns:Blog" minOccurs="0" maxOccurs = "unbounded" />

  17. </xsd:sequence>

  18. </xsd:complexType>

  19. </xsd:element>

  20. <xsd:element name="SearchCriteria">

  21. <xsd:complexType>

  22. <xsd:sequence>

  23. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  24. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  25. </xsd:sequence>

  26. </xsd:complexType>

  27. </xsd:element>

  28. <xsd:complexType name="Blog">

  29. <xsd:sequence>

  30. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  31. <xsd:element name="AbstractDetail" type="xsd:string" nillable="true"/>

  32. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  33. </xsd:sequence>

  34. </xsd:complexType>

  35. </xsd:schema>

The next in developing our web services is defining our contract, the WSDL file.
Here is the complete version the WSDL file.
Essentilly we are improting the xsd file which we had created in the earlier step to use them in the wsdl
Then create the message parts, the port and the binding operation for the blog search service. This is self explanatory.
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <definitions name="BlogSearch" targetNamespace="http://com.tejakantamneni/definitions"

  3. xmlns=""

  4. xmlns:soap=""

  5. xmlns:wsdl=""

  6. xmlns:xsd=""

  7. xmlns:tns="http://com.tejakantamneni/definitions"

  8. xmlns:schema="http://com.tejakantamneni/schemas">

  9. <wsdl:types>

  10. <xsd:schema targetNamespace="http://com.tejakantamneni/definitions" xmlns:schema="http://com.tejakantamneni/schemas">

  11. <xsd:import namespace="http://com.tejakantamneni/schemas" schemaLocation="../schemas/BlogSearch.xsd"/>

  12. </xsd:schema>

  13. </wsdl:types>

  14. <wsdl:message name="BlogSearchRequest">

  15. <wsdl:part name="BlogSearchRequest" element="schema:BlogSearchRequest"/>

  16. </wsdl:message>

  17. <wsdl:message name="BlogSearchResponse">

  18. <wsdl:part name="BlogSearchResponse" element="schema:BlogSearchResponse"/>

  19. </wsdl:message>

  20. <wsdl:portType name="BlogSearchService">

  21. <wsdl:operation name="BlogSearchOperation">

  22. <wsdl:input message="tns:BlogSearchRequest" name="BlogSearchRequest" />

  23. <wsdl:output message="tns:BlogSearchResponse" name="BlogSearchResponse" />

  24. </wsdl:operation>

  25. </wsdl:portType>

  26. <wsdl:binding name="BlogSearchBinding" type="tns:BlogSearchService">

  27. <soap:binding style="document" transport=""/>

  28. <wsdl:operation name="BlogSearchOperation">

  29. <soap:operation soapAction=""/>

  30. <wsdl:input name="BlogSearchRequest">

  31. <soap:body use="literal" />

  32. </wsdl:input>

  33. <wsdl:output name="BlogSearchResponse">

  34. <soap:body use="literal" />

  35. </wsdl:output>

  36. </wsdl:operation>

  37. </wsdl:binding>

  38. <wsdl:service name="BlogSearchService">

  39. <wsdl:port binding="tns:BlogSearchBinding" name="BlogSearchBindingPort">

  40. <soap:address location="http://localhost:8080/spring-ws-test/BlogSearch.soap"/>

  41. </wsdl:port>

  42. </wsdl:service>

  43. </definitions>

next step is creating the JAXB objects for your xsd elements using xjc compiler. you can either craft the JAXB objects by hand or just
use the xjc compiler. I prefer the later one. see for more details. (My Intellij Idea supports generating JAXB objects directly from xsd).

(Posting all the code is not practical, So I am moving here ahead posting the important parts)
Here is the endpoint
  1. /*

  2. * To change this template, choose Tools | Templates

  3. * and open the template in the editor.

  4. */
  5. package com.teja.service.endpoint;
  6. import com.teja.Blog;
  7. import com.teja.BlogSearchRequest;
  8. import com.teja.BlogSearchResponse;
  9. import com.teja.SearchCriteria;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.GregorianCalendar;
  13. import java.util.List;
  14. import javax.xml.datatype.DatatypeConfigurationException;
  15. import javax.xml.datatype.DatatypeFactory;
  16. import javax.xml.datatype.XMLGregorianCalendar;
  17. import javax.xml.transform.Source;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.oxm.Marshaller;
  20. import;
  21. import;
  22. import;
  23. import;

  24. /**

  25. * @author Teja Kantamneni
  26. * @version 1.0 Aug 25, 2008 - 11:30:49 AM
  27. */

  28. @Endpoint
  29. public class BlogSearchEndpoint {

  30. public static final String BLOG_SEARCH_ACTION = "";

  31. @Autowired
  32. Marshaller marshaller;

  33. @SoapAction(BLOG_SEARCH_ACTION)
  34. // public Source searchBlogs(@XPathParam("/sch:BlogSearchRequest/sch:SearchCriteria/sch:Title") String title, @XPathParam("/sch:BlogSearchRequest/sch:SearchCriteria/sch:PublishedDate") String publishedDate) throws DatatypeConfigurationException {
  35. public BlogSearchResponse searchBlogs(BlogSearchRequest blogSearchRequest) throws DatatypeConfigurationException {
  36. BlogSearchResponse blogSearchResponse = new BlogSearchResponse();
  37. List<Blog> resultBlogs = new ArrayList<Blog>();

  38. DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
  39. GregorianCalendar gregorianCalendar = new GregorianCalendar();
  40. gregorianCalendar.setTime(new Date());
  41. XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);

  42. Blog b = new Blog();
  43. b.setAbstractDetail("Abstract details -teja");
  44. b.setTitle("Teja test");
  45. b.setPublishedDate(xmlGregorianCalendar);

  46. resultBlogs.add(b);
  47. for (Blog blog : resultBlogs) {
  48. blogSearchResponse.getBlogList().add(blog);
  49. }
  50. return blogSearchResponse;
  51. }
  52. }

now the last and more important step, putting all the things together to deploy the service,configuring the spring-ws-servlet.xml

First and the most important point here is I am autowiring the endpoint by using the annotation @Endpoint.

So in the context.xml, we are defining the wsdl to be exposed as a bean using the class
I am specifying the JAXBMarshaller and injecting all the jaxb classes.
I am also configuring a couple of beans for validating and logging each and every request and response.

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns=""

  3. xmlns:xsi=""

  4. xmlns:context=""

  5. xmlns:jee=""

  6. xmlns:lang=""

  7. xmlns:util=""

  8. xmlns:p=""

  9. xsi:schemaLocation="





  14. <bean id="BlogSearch" class=""

  15. p:wsdl="/wsdls/BlogSearch.wsdl"/>

  16. <bean class="" >

  17. <constructor-arg ref="marshaller" index="0"/>

  18. </bean>

  19. <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">

  20. <property name="classesToBeBound">

  21. <list>

  22. <value>com.teja.Blog</value>

  23. <value>com.teja.BlogSearchRequest</value>

  24. <value>com.teja.BlogSearchResponse</value>

  25. <value>com.teja.SearchCriteria</value>

  26. </list>

  27. </property>

  28. <property name="schema" value="/schemas/BlogSearch.xsd" />

  29. </bean>

  30. <bean class="">

  31. <property name="interceptors">

  32. <list>

  33. <bean class=""/>

  34. <ref bean="validatingInterceptor"/>

  35. </list>

  36. </property>

  37. </bean>

  38. <bean class="">

  39. <property name="interceptors">

  40. <list>

  41. <bean class=""/>

  42. <ref bean="validatingInterceptor"/>

  43. </list>

  44. </property>

  45. </bean>

  46. <bean id="validatingInterceptor"

  47. class=""

  48. p:schema="/schemas/BlogSearch.xsd"

  49. p:validateRequest="true"

  50. p:validateResponse="true"/>

  51. <bean class="">

  52. <property name="namespaces">

  53. <props>

  54. <prop key="sch">http://com.tejakantamneni/schemas</prop>

  55. <prop key="xs"></prop>

  56. </props>

  57. </property>

  58. </bean>

  59. <!-- scan classes for dependency annotations -->

  60. <context:component-scan base-package="com.teja"/>

  61. <context:annotation-config/>

  62. <bean class="">

  63. <property name="order" value="2"/>

  64. </bean>

  65. </beans>

you can access the wsdl at http://localhost:8080/spring-ws-test/wsdl/BlogSearch.wsdl