Struts2をやってみる (5) - struts.xmlに定義する事なくActionをテストする -

2013-09-17T00:00:00+00:00 Java Struts2

単純に言うと、struts.xmlにを定義せずにテストクラスにアクションクラスを書いてそいつをregisterしてテストするっていう方式。どうやるのか不明だったので色々Struts2のソースを探ってみると

package sample.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.dispatcher.StreamResult;
import org.junit.Test;

import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static com.opensymphony.xwork2.ActionSupport.*;

public class IndexActionTestCase extends StrutsTestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        ActionConfig actionConfig = new ActionConfig.Builder(
            "",
            "",
            TestAction.class.getName()
        ).addResultConfig(
            new ResultConfig.Builder(SUCCESS, StreamResult.class.getName()).build()
        ).build();

        // Struts2デフォルトのPackageConfigはstruts-defaultで取得可能
        PackageConfig defaultPackageConfig = configuration.getPackageConfig("struts-default");

        PackageConfig packageConfig = new PackageConfig.Builder("test")
            .addActionConfig("test", actionConfig)
            .addParent(defaultPackageConfig)
            .namespace("/")
            .build();

        configuration.addPackageConfig("test", packageConfig);
        configuration.rebuildRuntimeConfiguration();
    }

    @Test
    public void test_dynamic() throws Exception {
        ActionProxy p = getActionProxy("/test.action");
        assertThat(p.execute(), is(SUCCESS));

        // わざとずっこけさせる
        assertThat(response.getContentAsString(), is("hoge"));
    }

    public static class TestAction extends ActionSupport {

        private static final long serialVersionUID = 1L;

        @Override
        public String execute() throws IOException {
            return SUCCESS;
        }

        public InputStream getInputStream() {
            return new ByteArrayInputStream("hoge fuga foobar".getBytes());
        }
    }
}

んな感じかなと。結果どうなるかと

てな感じ。こういう仕組みをデフォで用意してて欲しいんですが (あるのかどうかですら不明)

HBaseのTableReducer Struts2をやってみる (4) - StrutsResultSupportクラスを作る -