Ivan's Blog

Vague mumblings about all sorts of things. Java, Agile, Open Source...

Friday, November 05, 2004

Spring really eases testing

I've been racking my brain for a long time about how to effectively test web applications - setting up preconditions for tests (database data or simply a flag in the session).

I decided to use Spring for my current project right from the start. I had never used it before, but after a little reading it didn't make sense not to use it!

One of the reasons I decided on Spring, it claimed to help with testing due to its use of Inversion of Control (Ioc) and external wiring of applications via a (set of) simple XML file(s).

I was struggling on how I was going to test two simple use cases:
  1. A user logs in who has some stored items.
  2. A user logs in who has no stored items.

I had already checked the controller with a standard unit test, this felt more like an integration test.

I created a couple of Mock business objects and wired them together using Spring so that one user had some items and the other had none - this hid the persistance layer (which is already tested and would confuse the issue). At this point though I haven't coded the login mechanism so the problem was how to tell the system who the user was (without putting temporary test code into the system).

The answer, HandlerInterceptor. Handler interceptors are processed in a chain prior to control actually being passed to the Controller proper. I simply added a TestSetupInterceptor to the start of the chain. This class looks for request parameters with the prefix "test_", for example "test_userId". It then performs a bit of set up in the session object for that user. In this case user 1 had a couple of items added to the Mock business object, where as the other user had no such work done. Control is then passed on to the actual production code and out pops the correct web page representing the two states.

I really appreciate the cleanness of this approach, use the production configuration and the interceptor comes no where near the whole set up, use the test configuration and we are off again. No fiddling in any java, no recompilation to put things in to test mode. Just nice and simple.

Labels:

0 Comments:

Post a Comment

<< Home