package org.seasar.struts;

import org.apache.struts.action.Action;
import org.seasar.extension.unit.S2TestCase;
import org.seasar.framework.container.ComponentNotFoundRuntimeException;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;

/**
 * @author kimura
 */
public class ActionUtilTest extends S2TestCase {
    private Action firstInstance = null;
    private Action secondInstance = null;

    public ActionUtilTest(String name) {
        super(name);
    }

    protected void setUp() {
        SingletonS2ContainerFactory.init();
    }

    public void testCreateActionWithClassName() {
        firstInstance = ActionUtil.createActionWithClassName("org.seasar.struts.Test1Action");
        secondInstance = ActionUtil.createActionWithClassName("org.seasar.struts.Test1Action");
        assertTest1Action();

        firstInstance = ActionUtil.createActionWithClassName("org.seasar.struts.Test2Action");
        secondInstance = ActionUtil.createActionWithClassName("org.seasar.struts.Test2Action");
        assertTest2Action();

        firstInstance = ActionUtil.createActionWithClassName("org.seasar.struts.Test3Action");
        secondInstance = ActionUtil.createActionWithClassName("org.seasar.struts.Test3Action");
        assertTest3Action();
    }

    public void testCreateActionWithComponentName() {
        firstInstance = ActionUtil.createActionWithComponentName("/test1");
        secondInstance = ActionUtil.createActionWithComponentName("/test1");
        assertTest1Action();

        firstInstance = ActionUtil.createActionWithComponentName("/test2");
        secondInstance = ActionUtil.createActionWithComponentName("/test2");
        assertTest2Action();

        try {
            firstInstance = ActionUtil.createActionWithComponentName("/test3");
            fail();
        } catch (ComponentNotFoundRuntimeException e) {
            // success
        }
    }

    private void assertTest1Action() {
        assertSame(firstInstance, secondInstance);
        assertTrue(firstInstance instanceof org.seasar.struts.Test1Action);
        assertFalse(((Test1Action) firstInstance).isExecutedInitMethod());
        assertTrue(((Test1Action) firstInstance).hasService());
    }
    private void assertTest2Action() {
        assertNotSame(firstInstance, secondInstance);
        assertTrue(firstInstance instanceof org.seasar.struts.Test2Action);
        assertTrue(((Test2Action) firstInstance).isExecutedInitMethod());
    }
    private void assertTest3Action() {
        assertSame(firstInstance, secondInstance);
        assertTrue(firstInstance instanceof org.seasar.struts.Test3Action);
        assertFalse(((Test3Action) firstInstance).isExecutedInitMethod());
        assertTrue(((Test3Action) firstInstance).hasService());
    }
}