One of the useful features of Struts2 is that the method in your Action that you want the framework to execute does not have to be called execute. While this doesn’t sound like much it means that you can re-use the majority of an Action without having to go down the route of inheriting from a base class.
Following up from my previous post of unit testing actions with annotation based validation, someone asked me how you can specify validation on a method other than action, and here’s how. Continue reading
Unit testing Struts actions became a lot easier in Struts 2. With actions being POJOs rather than having to extend a base Action class, unit tests are incredibly simple. Throw in mocking any dependencies using something like Mockito and you have a class that can be unit tested in complete isolation…with one caveat, validation.
While the easiest way to implement validation is to extend the ActionSupport class, you can implement the Validateable and ValidationAware interfaces yourself. Validating the action normally requires you to somehow implement a little bit of the container. This can be done easily enough but it breaks the idea of unit tests just being about the class and starts to wander into the territory of integration tests. Not a big problem really but it can be a real pain in the arse when you have a large project with several hundred tests that all require the initialisation and tear-down of the Struts2 stack.
In Struts 2.0.x, there was a way round this. The class ActionValidatorManagerFactory was provided in the source code that allowed you to create an instance of the ActionValidatorManager. You could use this to call validate on the execute method and you were done.
In Struts 2.1.x, for reasons unknown, the ActionValidatorManager class has been removed. So how are you supposed to validate your actions now? The answer is to re-implement it yourself. Continue reading