Struts2のInterceptorをJUnitでテストしてみました。
そのときちょっと面倒なのがActionInvocation づくり。
コレを使えば割と簡単です。
com.opensymphony.xwork2.mock.MockActionInvocation
HttpServletRequest を作りたいときはコレ。
org.springframework.mock.web.MockHttpServletRequest
もう、リクエストやらセッションやらいろいろ値を入れられます。
// アクションコンテキスト
HashMap<String, Object> contextMap = new HashMap<String, Object>();
ActionContext context = new ActionContext(contextMap);
// リクエスト
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("IPアドレス");
request.addHeader("User-Agent", "ユーザエージェント");
context.put(StrutsStatics.HTTP_REQUEST, request);
// セッション
HashMap<String, Object> session = new HashMap<String, Object>();
session.put("セッションキー", "セッション値");
context.setSession(session);
// パラメータ
HashMap<String, Object> parameters = new HashMap<String, Object>();
parameters.put("パラメータ名", "パラメータ値");
context.setParameters(parameters);
// ActionInvocation を準備
MockActionInvocation invocation = new MockActionInvocation();
YourAction action = new YourAction();
invocation.setAction(action);
invocation.setInvocationContext(context);
// インターセプター呼び出し
YourInterceptor interceptor = new YourInterceptor();
interceptor.intercept(invocation);
// インターセプターで何か注入していれば、actionから取り出して値を検査
もっといろいろできるでしょう。
ま、PHPならこんな苦労はしなくてもいいですけどね。


