Testing struts actions with the StrutsTestCase tests much more than just the logic in the action class itself, which is normally what you want to do in a well isolated and simple unit test. I am not interested in whether urls are correctly mapped or request parameters are set on my models by struts. This is something the struts developers do themselves, I assume, and for me it is actually more of an integration test.
So, to my issue. Trying to unit test my actions I ran into a new issue the other day testing an action using the getText(..) method. This particular method, in the end, locates package resources in it's own directory (from the action class) and parent packages until a resource is perhaps finally found. This requires the environment to know about which action class is executing. I've been trying to mock this condition away with combinations of easyMock and the struts bundled mock classes. To no avail.
The problem here is a classic one when you try to unit test. It is because I have extended the bundled ActionSupport (for convenience) and it contains:
private final transient TextProvider textProvider =
new TextProviderFactory().createInstance(getClass(), this);
private final ValidationAwareSupport validationAware =
new ValidationAwareSupport();
The ValidationAwareSupport is just a datastructure to decrease code size of the validation aware class and has no external dependencies, which makes it a non-issue.
The TextProviderFactory however, is a big issue. Skipping a few details, digging into it, it depends on just about everthing. There are utility methods accessing action context and the valuestack and so forth. Wanting to avoid the execution context, in this case the action context (and possibly more), this should of course be decoupled.
I have already, since long back written my own ActionSupport since I didn't want it to be serializable. And, now decoupling the TextProvider is not very hard. I just add an interceptor that injects the TextProvider into the action during struts invocation. After this I'm free to provide a truly decoupled mock TextProvider in my unit test.
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Object action = invocation.getAction();
if (action instanceof TransientActionSupport) {
if (logger.isDebugEnabled()) {
logger.debug("Setting text provider on action");
}
((TransientActionSupport)action).setTextProvider(
new TextProviderFactory().createInstance(
action.getClass(), (LocaleProvider)action));
}
return invocation.invoke();
}
The next step is just to add the interceptor to your default interceptor stack, and you have the same functionality in your webapp as before.
No comments:
Post a Comment