Junit用Spring测试Struts2动作

时间:2013-08-26 07:28:32

标签: spring struts2 junit

我想测试Struts操作,但我遇到了以下问题:

SEVERE:   [09:16.218] Error building bean

看来Spring没有依赖注入。 实际上,如果我创建一个默认构造函数,我会得到一个NPE,因为该服务没有实例化。我的单元测试扩展了StrutsSpringTestCase,那么为什么我的Action不能正确实现?

这是我的行动:

public ControllerAuthentification(LdapUserService service) {
    this.ldapUserService = service;
}

public String connection() {
    if (userLdap != null) {
        ldapUserService.save(userLdap);
        addActionMessage(getText("success.connect"));
        return SUCCESS;
    }
    return INPUT;
}

单元测试:

public class ControllerAuthentificationTest extends StrutsSpringTestCase {

    public void testConnection() throws Exception {

        request.setParameter("userLdap.login", "login");
        request.setParameter("userLdap.password", "password");
        proxy = getActionProxy("/connection");
        ControllerAuthentification action = (ControllerAuthentification) proxy.getAction();
        String result = proxy.execute();

       assertTrue("it would be true", result.equals(Action.SUCCESS));
    }
}

的applicationContext

<bean id="ldapUserService" class="sword.plateformetest.service.impl.LdapUserServiceImpl" />
<bean id="ldapUserAuthAction" scope="prototype"
    class="sword.plateformetest.action.ControllerAuthentification">
    <constructor-arg ref="ldapUserService" />
</bean>

和我的web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

堆栈追踪:

SEVERE:   [56:08.596] Error building bean
2013-08-26 13:56:08,600 ERROR sword.plateformetest.action.ControllerAuthentificationTest.testConnection:37 - error
Unable to intantiate Action!
    at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:299)
    at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
    at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
    at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    at org.apache.struts2.StrutsTestCase.getActionProxy(StrutsTestCase.java:137)
    at sword.plateformetest.action.ControllerAuthentificationTest.testConnection(ControllerAuthentificationTest.java:34)

1 个答案:

答案 0 :(得分:1)

您应该延长StrutsSpringJUnit4TestCase。这是我对它的回答:

How to test Struts2 action in Junit 4 way?

您可能必须添加struts2-junit-plugin依赖项。

对于@Kevin Rave,您可能需要在URI的末尾添加“.do”。我有完全相同的问题并附加解决了它。