今さらながらStruts1系のActionやFormをJUnitでテストする方法

StrutsのActionやFormをJUnitでテストするには StrutsTestCase http://strutstestcase.sourceforge.net/ を使う。

設定ファイルを置く場所は厄介。次のようにマニュアル通り記述しても

	public void setUp() throws Exception {
		super.setUp();

		// コンテキストパスの指定
		setContextDirectory(new java.io.File("."));
		// Servletコンフィグファイル(web.xml)の指定
		setServletConfigFile("/src/main/webapp/WEB-INF/web.xml");
		// Strutsコンフィグファイルの指定
		setConfigFile("/src/main/webapp/WEB-INF/struts-config.xml");
	}

下記のようにエラーが出る。

致命的: Error initializing action servlet
javax.servlet.UnavailableException: /WEB-INF/web.xmlが見つかりません

解決策が浮かばない。テストを実行する時だけ /src/main/webapp/WEB-INF/web.xml を /WEB-INF/web.xml にコピーするとひとまずは動くようになる。

簡単なテストコードはこんな感じか↓

	@Test
	public final void testValidateActionMappingHttpServletRequest() {
		setRequestPathInfo("/helloWorld.do");
		addRequestParameter("country", "FR");
		actionPerform();
		verifyNoActionErrors();
		verifyForward("success");
	}


ActionFormのvalidateが呼ばれるかどうかはstruts-config.xmlの設定次第。
validate=trueなら呼ばれるし、falseなら呼ばれない。

	<action-mappings>
		<action path="/helloWorld" type="com.mkyong.common.action.HelloWorldAction"
			name="helloWorldForm" validate="true">
			<forward name="success" path="/HelloWorld.jsp" />
		</action>
	</action-mappings>

※参考にしたサイト
Test-Driven Development Using StrutsTestCase http://onjava.com/pub/a/onjava/2005/10/26/test-driven-development-using-strutstestcase.html
Struts Hello World Example http://www.mkyong.com/struts/struts-hello-world-example/