0

我正在为使用 JUnit 的 Struts2、Spring、Hibernate 的项目编写集成测试用例。

我的测试类扩展了StrutsSpringTestCase. 应用程序需要登录/会话来调用任何操作。以下是代码:

@Test
public void testGetActionProxy() throws Exception {
    
    ActionProxy proxy;
    String result;
    ActionContext.getContext().setSession(createUserSession()); // Not sure if this is needed here. But in order to get the session working, I need this.

    proxy = initAction("cInfo");
    assertNotNull(proxy);
        
    CustInfo action = (CustInfo) proxy.getAction();
    result = proxy.execute();
    assertEquals(Action.SUCCESS, result);
}

initAction()方法:

private ActionProxy initAction(String actionUri) {
    ActionProxy proxy = getActionProxy(actionUri);
    
    ActionContext.setContext(proxy.getInvocation().getInvocationContext());  // I tried this line of code to get the ServletActionContext.getMapping().getName() to work. But no use.
    
    ActionContext actionContext = proxy.getInvocation().getInvocationContext();
    actionContext.setSession(createUserSession()); // This is for setting a session
    return proxy;
 }

在使用此方法之前,它会加载所有配置文件。struts.xml jpaContext.xml,beans.xml等。

我的 Action 类CustInfo实现ServletRequestAware了,它有一个方法getActionName,如下所示:

 return ServletActionContext.getActionMapping().getName();

当我调用时会调用它result = proxy.execute();。所以请求失败。

问题1:为什么会返回null?我认为ServletActionContext是自动启动的,所以它应该返回一个值。但它不是。如果它没有初始化,初始化的正确位置在哪里以及如何初始化?

getActionProxy我在通话后尝试了以下操作。但它仍然没有工作。

ServletActionContext.setContext(proxy.getInvocation().getInvocationContext());

问题2:要设置会话,之前getActionProxy(),我必须打电话,

ActionContext.getContext().setSession(createUserSession());

再一次,之后getActionProxy

ActionContext actionContext = proxy.getInvocation().getInvocationContext();
actionContext.setSession(createUserSession());

设置会话。我想,这里有问题。

问题 3:看起来,这里有几个上下文在起作用applicationContextActionContext ServletContextServletActionContext

当我的测试类扩展StrutsSpringTestCase类时,我猜applicationContext是初始化了。但我不确定其他情况。在哪里初始化它们?

编辑:

对源代码的进一步调查揭示了一个问题。当我调用时ServletActionContext.getActionMapping(),在内部调用它ActionContextget()方法。

public Object get(String key) {
    return context.get(key);
}

context是一个对象的映射,它在其中寻找struts.actionMapping不存在的键的值。所以,返回null。但不知道为什么它在那里。它不是空的。它有其他键/值。

4

1 回答 1

0

您的问题的答案:

ServletActionContext.getActionMapping()从动作上下文返回映射,如果它没有设置,那么你得到null.

您不应该手动设置会话,执行操作时会创建会话。

不要弄乱不同的类ActionContext,ServletContextServletActionContext. 您不应该对初始化这些对象做任何事情,因为它是由超类完成的StrutsSpringTestCase

public void testGetActionMapping() {
    ActionMapping mapping = getActionMapping("/cInfo.action");
    assertNotNull(mapping);
    assertEquals("/", mapping.getNamespace());
    assertEquals("cInfo", mapping.getName());
}

public void testGetActionProxy() throws Exception {        
    ActionProxy proxy = getActionProxy("/cInfo.action");
    assertNotNull(proxy);

    CustInfo action = (CustInfo) proxy.getAction();
    assertNotNull(action);

    String result = proxy.execute();
    assertEquals(Action.SUCCESS, result);
}
于 2014-10-31T18:50:53.080 回答