Tuesday, September 25, 2007

Testing HTTPS Secured Actions with StrutsTestCase

If you have secured some Struts actions using SSLEXT's Struts plugin (org.apache.struts.action.SecurePlugIn) you will have to invoke the action over https, else SSLEXT will redirect to the configured HTTPS port.

So in order to test secured actions using MockStruts test cases you need to inform SecurePlugIn that the request came over https. This is quite easy as the HttpServletRequestSimulator class that's used by MockStruts has a setScheme method. All you have to do is set the scheme to HTTPS in the inherited request object before calling the actionPerform method in the test class.

e.g.


public class LoginTest extends MockStrutsTestCase {
public void testlogin() {
setConfigFile("/WEB-INF/struts-config.xml");
setRequestPathInfo("/login");
addRequestParameter("username", "test");
addRequestParameter("password", "test1234");

//set the request's scheme to HTTPS
request.setScheme("HTTPS");
//invoke action
actionPerform();

verifyNoActionErrors();
verifyForward("success");
}
}

Don' forget to click the +1 button below if this post was helpful.

Friday, September 7, 2007

Speed up MockStruts Test Execution by Caching Spring Context

If you are using MockStruts to test your Struts/Spring application most of your test execution time would be spent on initializing or trying to initialize the Spring context for each test method.

This is true if you use Spring's ContextLoaderPlugIn, where it tries to initialize a custom spring context using the parent context.

Spring will look for the parent context in the ServletContext object where it store it. Since MockStruts will create a new ServletContext for each test method Spring will try to create the context each time. This results in addition of about 4 second per test method (on my workstation).

Note: I'm using MappingDispatchAction with multiple actions in a single Action class, therefore I have mutiple test methods in a single test class too.

The above 4 second penalty per test method can be removed by simply caching and storing the Spring context in ServletContext object before each test execution. This reduced the execution time of the whole test suite drastically in the application I was working on.

In order to achieve the above I used a base class extending MockStrutsTestCase as shown below and used it as the parent class for all the Struts test cases


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import servletunit.struts.MockStrutsTestCase;

public abstract class BaseStrutsTestCase extends MockStrutsTestCase {

/** Spring context */
private static ApplicationContext applicationContext;

/**
* Setup Spring context
*
* @throws Exception
* exception
*/
protected void setUp() throws Exception {
super.setUp();

if (applicationContext == null) {
// this is the first time. Initialize the Spring context.
applicationContext = (new ContextLoader()).initWebApplicationContext(getRequest().getSession()
.getServletContext());
} else {
// Spring context is already initialized. Set it in servlet context
// so that Spring's ContextLoaderPlugIn will not initialize it again
getRequest().getSession().getServletContext().setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
}
}

/**
* Returns the Spring application context
*
* @return initialized Spring application context
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}

}


Also remember to set forkMode to perBatch or once in ants junit task as shown below if you have set the fork attribute to true.


<junit fork="true" forkmode="once" haltonfailure="">
...

</junit>

Don' forget to click the +1 button below if this post was helpful.

Wednesday, August 8, 2007

Unit Testing with Junit, Spring and Hibernate - Part 2

This is a continuation from my previous post on Spring and MockStrutsTestCase and focus on testing Hibernate DAO's. As I mentioned in the previous post, Spring framework provides a nifty base class (AbstractTransactionalDataSourceSpringContextTests) that provides automatic transaction rollback, exposing a JDBC template to interact with the DB and auto wiring of beans.

Lets take a simple DAO class that save a User object to the database:

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
public void save(User user) {
getHibernateTemplate().save(user);
}
}

Now in order to test this you would write a test class as below extending from AbstractTransactionalDataSourceSpringContextTests class.


public class UserDaoTest extends AbstractTransactionalDataSourceSpringContextTests {
private UserDao userDao;
private SessionFactory sessionFactory = null;

protected String[] getConfigLocations() {
return new String[]{"test-spring-config.xml"};
}

/**
* Spring will automatically inject UserDao object on startup
* @param userDao
*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

/**
* Spring will automatically inject the Hibernate session factory on startup
* @param sessionFactory
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

/**
* Test the save method
*
*/
public void testSave(){
String query = "select count(*) from user where first_name = 'Firstname'";
int count = jdbcTemplate.queryForInt(query);
assertEquals("A user already exists in the DB", 0, count);

User user = new User();
user.setFirstName("Firstname");

userDao.saveUser(user);

// flush the session so we can get the record using JDBC template
SessionFactoryUtils.getSession(sessionFactory, false).flush();

count = jdbcTemplate.queryForInt(query);
assertEquals("User was not found in the DB", 1, count);
}
}

The test class has to implement the protected String[] getConfigLocations() method from the base class and return a String array of Spring config files which will be used to initialize the Spring context.

UserDao and SessionFactory properties are defined with the setter methods and the base class will take care of injecting them automatically from the Spring context. Auto wiring will not work if there are multiple objects implementing the same interface. In such a case you can remove the setter method and retrieve the object using the exposed applicationContext as below.

   /**
* Overridden method from base class which gets called automatically
*/
protected void onSetUpBeforeTransaction() throws Exception {
super.onSetUpBeforeTransaction();
userDao = (UserDao) applicationContext.getBean("userDao");
}

The base class also exposes a JDBC template object (jdbcTemplate) that can be used to query data or setup test data in the database. Note that you need to have a data source and a transaction manager defined in your Spring config in order to use the AbstractTransactionalDataSourceSpringContextTests base class. The data source defined in the config file will be bound to the exposed JDBC template.

In the testSave method first we verify there is no record in the User table where first name equals to 'Firstname' using the jdbc template object. Then we call the save method on the UserDao passing it a User object.

Now we simple verify there is a record in the table where first name equals to 'Firstname'. Before running the query we flush the current Hibernate session to make sure jdbcTemplate can see the newly added record.

Thats it and when the testSave method exits the current transaction will be rolled back and the record inserted to the User table will not be saved. This is great as your test database will always be at a know state at the start and end of a test method.

The spring config file will like below (test-spring-config.xml) :

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean name="userDao" class="com.dao.UserDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="mappingResources">
<list>
<value>hibernates/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property>
</bean>


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
<property name="username" value="test" />
<property name="password" value="test" />
</bean>


<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>

</beans>

Don' forget to click the +1 button below if this post was helpful.

Friday, July 27, 2007

How to Properly Iterate a Collection in Java

There are multiple ways to iterate a collection in Java among many other things but that doesn't mean all are equally elegant or easy on the eyes. Just as some ways to skin a cat are messier than others (Not that I have ever skinned a cat or any other animal for that matter). Anyhoo I'm making this post in hopes of at least few developers starting on Java will see it before starting to write code in a commercial project.

I came across a code base of a project that was developed mostly by a bunch of junior developers and most of the code that iterates a collection was in the following format

List administrators = getAdministrators();

if (administrators.size() > 0) {
Iterator administratorsItr = administrators.iterator();
Administrator administrator = null;
while (administratorsItr.hasNext()) {
administrator = (Administrator) administratorsItr.next();
//rest of the code block removed
}
}
}

Just looking at that piece of code made my head spin :). The worst part was that this is the style most of the junior developers had adopted and could be seen all over the code base.

Just for the record I would have written it in the following way (actually would have let the IDE write it for me)

List administrators = getAdministrators();

for (Iterator iter = administrators.iterator(); iter.hasNext();) {
Administrator administrator = (Administrator) iter.next();
//rest of the code block removed
}

The above two code blocks achieve the same thing, the difference been, first is 9 lines long and the second is 4 lines. Most importantly you can figure out whats going on easily by looking at the second code block.

The worst part is IDEs like IntelliJ IDEA will write it for you. All you have to do is type itco and press ctrl + space keys just after the List administrators = ... line.

I don't know if there is something similar on Eclipse but you can import all these nifty IDEA Live Templates into Eclipse. Just head over to this page where you can find the xml file and instructions on how to import the file.

Don' forget to click the +1 button below if this post was helpful.