Testing controllers with Struts2

Posted in: Archive

We started using Struts 2 for the first time in our eProspectus project. In fact we're using Hibernate/JPA+Spring+Struts2.

To me, one of the most obvious advantages that Struts 2 gave us was the ability to unit test our controllers. Before now, our project architecture usually consisted of Hibernate+Servlets+JSTL JSPs. We were only unit testing our model and DAO. Though there are ways for us to unit test Servlets, it's not as straightforward as simply instantiating an action class and chucking a load of data at it. Servlets would require mocking up a request for example.

What I didn't like though, was keeping track of what parameters were being passed in and what objects were loaded in the action classes. I often fell foul of writing tests that passed and seeing errors in the web app. It was simply because the params or the objects loaded for the action classes in the tests didn't match up with the web app.

I think it's simply a reflection of some of our (my!) action classes. Not breaking the OGNL debugger console would have probably really helped. We really liked that console.

The eProspectus project was also my first opportunity to use Java Annotations. Support for annotations were provided by Spring, Hibernate's implementation of JPA and in Struts 2 action classes. Obviously, you're no longer writing XML for your most of your configs (just a couple). So there aren't masses of xml files that accompany each of your model classes for example - halving the number of files you'd have. The biggest win for me is being able to instantly see the config for a class in the code itself, rather than opening up a separate XMl file and switching between the two files. It just made life so much easier.

There was some pain in getting to grips with Struts 2, especially when we ignored the warnings in the docs that said certain features were experimental (I actually can't remember what that was now...) but we've built up a significant amount of new knowledge and I'm especially happy to have Spring and JPA under my belt.

Posted in: Archive