事务性SpringJUnit4测试失败

时间:2016-12-16 10:34:31

标签: spring jpa junit aspectj spring-roo

我们对Spring Web应用程序的事务性JUnit测试失败。

具体来说:如果我分别用maven执行每个测试,它们会贯穿:

mvn -Dtest=Test1
mvn -Dtest=Test2

如果我执行

mvn -Dtest=Test1,Test2 

我在其中一个测试中遇到JPA错误:

Could not open JPA EntityManager for transaction; nested exception is
    java.lang.IllegalStateException:
        Attempting to execute an operation on a closed EntityManagerFactory."
        type="org.springframework.transaction.CannotCreateTransactionException"
        org.springframework.transaction.CannotCreateTransactionException:
            Could not open JPA EntityManager for transaction; nested exception is
                java.lang.IllegalStateException:
                    Attempting to execute an operation on a closed EntityManagerFactory.
                        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.verifyOpen(EntityManagerFactoryDelegate.java:338)
                        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:303)
                        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:336)
                        at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:302)
                        at org.springframework.orm.jpa.JpaTransactionManager.createEntityManagerForTransaction(JpaTransactionManager.java:449)
                        at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:369)
                        at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
                        at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:439)
                        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
                        at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:64)
                        ...

如果我设置了surefire插件来为每个测试重新创建整个JVM,那么它们也会运行,这样做会花费大量时间。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${maven.surefire.version}</version>
    <configuration>
        <reuseForks>false</reuseForks>
        <forkCount>1</forkCount>
    </configuration>
</plugin>

应用程序设置:

  • Spring,Spring Roo(因此proxymode = asjectJ!)
  • Eclipselink as JPA Provider

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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="[packagename]">
    <context:exclude-filter expression=".*_Roo_.*" type="regex" />
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
<context:spring-configured />
<context:property-placeholder location="classpath*:META-INF/spring/*.properties" />
<context:annotation-config />

<bean class="org.springframework.orm.jpa.JpaTransactionManager"
    id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven mode="aspectj"
    transaction-manager="transactionManager" />

<bean
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" id="dataSource">
    <property name="driverClassName" value="${test_database.driverClassName}" />
    <property name="url" value="${test_database.url}" />
    <property name="username" value="${test_database.username}" />
    <property name="password" value="${test_database.password}" />
    <property name="testOnBorrow" value="true" />
    <property name="testOnReturn" value="true" />
    <property name="testWhileIdle" value="true" />
    <property name="timeBetweenEvictionRunsMillis" value="1800000" />
    <property name="numTestsPerEvictionRun" value="3" />
    <property name="minEvictableIdleTimeMillis" value="1800000" />
    <property name="validationQuery" value="SELECT 1" />
</bean>

<jdbc:initialize-database data-source="dataSource"
    ignore-failures="ALL">
    <jdbc:script location="${test_database.selectLocation}" />
    <jdbc:script location="${test_database.initLocation}" />
    <jdbc:script location="${test_database.dataLocation}" />
</jdbc:initialize-database>
</beans>

JUnit测试看起来像:

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:META-INF/spring/applicationContext.xml",
    "classpath:META-INF/spring/webmvc-config.xml" })
@TransactionConfiguration(transactionManager = "transactionManager")
@DirtiesContext
public class Test1 {

    @Autowired
    WebApplicationContext wac;

    private MockMvc mockMvc;

    @PersistenceContext
    EntityManager entityManager;

    @Before
    public void setup() throws Exception {
      this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    @Transactional
    public void getJSONTest() throws Exception {
    ...
    }
}

有没有人知道,这两个测试是如何连接的?必须为另一个关闭entityManager,但为什么以及如何?

任何想法都表示赞赏!

Edit1 :删除了@TransactionConfiguration和@DirtiesContext,但现在我得到了

No transaction is currently active; nested exception is
    javax.persistence.TransactionRequiredException

Edit2 :到目前为止,我一直在追踪这个问题,即我执行测试的顺序是一个漏洞。因此,测试不是彼此独立的。我尝试了几种注释和执行顺序的排列,每次都会产生不同的错误/行为。

现在,课程级别的设置是:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:META-INF/spring/applicationContext.xml",
    "classpath:META-INF/spring/webmvc-config.xml" })
@WebAppConfiguration
@Transactional
@DirtiesContext

我再次放置@DirtiesContext注释,因为新初始化的上下文似乎有时会有所帮助。

这里很难找到真正的问题,但我得出了一个具体的问题:

我在@Transactional中包装了我的测试类,在我的测试方法中我调用了

mockMvc.perform(MockMvcRequestBuilders.post(...))

,调用控制器方法。此控制器方法委托给另一个具有@Transactional方法的bean。在mockMvc.perform()返回之后,我检查了单元测试天气,该值已写入数据库。我知道这只有在事务提交到数据库或使用相同的Transaction / entityManager时才有效。是测试方法的事务,与被调用的控制器的事务相同,还是我们在这里讨论两个不同的entityManagers / transactions?

1 个答案:

答案 0 :(得分:0)

我会说@DirtiesContext正在这样做 - 请参阅此处http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

我会尝试:

  1. 删除@TransactionConfiguration(transactionManager =“transactionManager”) - 我认为根据你的spring xml配置没有必要
  2. 删除@DirtiesContext
  3. 然后尝试改善情况...... 这是我用来测试DAO层的设置(每个方法实际上都到达了真正的数据库,但是由于@Rollback,数据库永远不会被测试改变,因此测试不会互相干扰)

    function utoa(str) {
        return window.btoa(unescape(encodeURIComponent(str)));
    }
    
    function atou(str) {
        return decodeURIComponent(escape(window.atob(str)));
    }
    
    // Usage:
    utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
    atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
    
    utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
    atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"