3

我的项目架构是带有 Spring 集成和 JPA/Hibernate 的 Struts2。StrutsSpringTestCase 基类用于 JUnit 集成测试。

在正常情况下,web.xml 中的以下配置会从每个请求的开始到结束保持一个会话打开:

<filter>
    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

结果,所有延迟加载在所有服务中都可以正常工作。例如:

@Override
public Person find(int id) {
    Person person = personDao.find(id);

    // Take care of lazy loading before detaching the object for
    // the view layer...
    person.getGender().getCode();

    // Detach the object so that it can be used for data transfer
    // (as a DTO) without causing JPA issues and errors...
    getEntityManager().detach(person);

    return person;
}

现在......当我尝试运行集成测试时出现问题,这些测试独立于 web.xml 中的 OpenEntityManagerInViewFilter 配置。发生的情况是,由于从每个请求的开始到结束都没有会话保持打开状态,因此像“person.getGender().getCode()”这样的延迟加载语句不再起作用,并且我得到“无法初始化代理 - 无会话”错误。

我知道的一种解决方案是对存在延迟加载问题的服务方法强制使用 @Transactional 注释,这将导致会话从方法调用的开始到结束都打开。我测试了它并解决了问题:

@Transactional
@Override
public Person find(int id) {
    Person person = personDao.find(id);

    // Take care of lazy loading before detaching the object for
    // the view layer...
    person.getGender().getCode();

    // Detach the object so that it can be used for data transfer
    // (as a DTO) without causing JPA issues and errors...
    getEntityManager().detach(person);

    return person;
}

但是,这可能是矫枉过正,因为该方法在正常情况下不需要事务。我想知道是否有另一种不需要在服务方面妥协的解决方案。

有什么我可以添加到我的测试类(扩展 StrutsSpringTestCase)以保持会话打开的东西吗?或者在 Spring 或 JUnit 方面是否有一个优雅的配置解决方案?

这是我的 Spring 配置文件 - applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
        default-dependency-check="all"
        default-lazy-init="false"
        default-autowire="byName">


    <!-- *************** MAIN CONFIGURATION SECTION *************** -->

    <!-- Bean post-processor for JPA annotations. -->
    <!-- Make the Spring container act as a JPA container and inject an EnitityManager from
         the EntityManagerFactory. -->
    <bean   class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
            autowire="no"
            dependency-check="none" />


    <!-- ** Data Source Configuration ** -->
    <bean   id="dataSource"
            class="com.mchange.v2.c3p0.ComboPooledDataSource"
            destroy-method="close"
            autowire="no"
            dependency-check="none">
        <!-- Database configuration: -->
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost/**********" />
        <property name="user" value="**********" />
        <property name="password" value="**********" />
        <!-- C3P0 pooling properties configuration: -->
        <property name="acquireIncrement" value="4" />
        <property name="initialPoolSize" value="4" />
        <property name="minPoolSize" value="4" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="600" />
        <property name="maxConnectionAge" value="1800" />
    </bean>


    <!-- ** JPA Vendor Selection ** -->
    <bean   id="jpaVendorAdapter"
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
            autowire="no"
            dependency-check="none" />


    <!-- ** JPA Vendor and Entity Manager Configuration ** -->
    <bean   id="entityManagerFactory"
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
            autowire="no"
            dependency-check="none">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

                <!-- Have the JPA vendor manage the database schema: -->
                <prop key="hibernate.hbm2ddl.auto">create</prop>

                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
                <prop key="hibernate.max_fetch_depth">4</prop>
                <prop key="hibernate.jdbc.batch_size">1000</prop>

                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">false</prop>
            </props>
        </property>
    </bean>


    <!-- ** Transaction Manager Configuration ** -->
    <bean   id="transactionManager"
            class="org.springframework.orm.jpa.JpaTransactionManager"
            autowire="no"
            dependency-check="none">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>


    <!-- ** Transaction Annotation Configuration; classes/functions with @Transactional will
            get a framework transaction. ** -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- **** DETAILED SERVICE BEAN CONFIGURATION WAS TAKEN OUT TO SHORTEN THE FILE **** -->

</beans>

我会很感激任何指示。

编辑:

为了让事情更直观一点,当相关服务方法遇到延迟加载并且服务方法没有使用@Transactional 注释时,以下测试会生成一个异常,但是当服务方法使用@Transactional 注释时可以正常工作

public class ActionTest extends CustomActionTestBase {

    public ActionTest() {
        super("/web/someAction"); // the action to test
    }

    @Override
    public void testHelperActionLoggedIn() throws Exception {
        procApplyContinualSessionForAdmin(); // the numerous steps to get logged in

        procExecuteAction(
                helpGetPrimaryActionURI(),  // use the action URI set by the constructor above
                helpPrepareActionParams( )  // no parameters are passed to this action
            );

        procConfirmOutcome(ActionSupport.SUCCESS,0,0,0,false);
    }

}

注意:CustomActionTestBase 扩展了 StrutsSpringTestCase(它又扩展了一些 JUnit 的东西)。由于一些繁重的测试用例定制/自动化,我需要 CustomActionTestBase。

编辑:

我还尝试将@Transactional 添加到“testHelperActionLoggedIn()”测试方法本身,这并没有改变结果。

编辑:

此外,我尝试通过使用 @RunWith、@ContextConfiguration 和 @Test 进行注释来使事情更加特定于 Spring(按照 Aleksandr M 的指示)。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class ActionTest extends CustomActionTestBase {

    public ActionTest() {
        super("/web/someAction"); // the action to test
    }

    @Test
    @Override
    public void testHelperActionLoggedIn() throws Exception {
        procApplyContinualSessionForAdmin(); // the numerous steps to get logged in

        procExecuteAction(
                helpGetPrimaryActionURI(),  // use the action URI set by the constructor above
                helpPrepareActionParams( )  // no parameters are passed to this action
            );

        procConfirmOutcome(ActionSupport.SUCCESS,0,0,0,false);
    }

}

它导致出现在 JUnit 故障跟踪中的异常 - 无论出于何种原因,控制台中都没有异常输出。异常详情:

java.lang.NullPointerException
at org.apache.struts2.StrutsTestCase.getActionMapping(StrutsTestCase.java:196)
at org.apache.struts2.StrutsTestCase.getActionMapping(StrutsTestCase.java:206)
at com.mycompany.utils.test.CustomActionTestBase.examineActionMapping(CustomActionTestBase.java:402)
at com.mycompany.utils.test.CustomActionTestBase.procExecuteAction(CustomActionTestBase.java:158)
at com.mycompany.utils.test.CustomActionTestBase.execLoginActionForAdmin(CustomActionTestBase.java:505)
at com.mycompany.utils.test.CustomActionTestBase.procApplyContinualSessionForAdmin(CustomActionTestBase.java:106)
at com.mycompany.actions.web.ActionTest.testHelperActionLoggedIn(ActionTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

看起来它在获取动作映射时遇到了麻烦,这是以前没有的。

4

1 回答 1

1

您可以将@Transactional注释放在测试方法上,并且需要使用 spring 运行测试才能找到@Transactional注释。要在 Struts2 测试中使用 JUnit4,您需要扩展StrutsSpringJUnit4TestCase. 所以你的测试类应该是这样的:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class ActionTest extends StrutsSpringJUnit4TestCase {
  @Transactional
  @Test
  public void testHelperActionLoggedIn() throws Exception {
    // ...
  }
}

注意:如果需要获取ActionProxy,可以通过调用getActionProxy方法获取。您可能需要为其创建新的会话映射,然后您可以调用execute.

ActionProxy actionProxy = getActionProxy("/action");
Map<String, Object> sessionMap = new HashMap<String, Object>();
actionProxy.getInvocation().getInvocationContext().setSession(sessionMap);
actionProxy.execute();

但是,如果您不需要参考,ActionProxy那么您可以使用executeAction方法以这种方式执行操作,您不需要创建新的会话映射。

executeAction("/action");
于 2013-10-01T06:56:47.227 回答