使用JPA和Spring进行集成测试

时间:2011-03-24 15:43:57

标签: java maven-2 jpa integration-testing dbunit

我有一个Spring / JPA Web应用程序,我想为其编写一些测试。理想情况下,我希望能够:

  • 在运行测试之前创建测试数据库模式(来自JPA注释类)
  • 在其自己的事务中运行每个测试方法,该事务在测试完成时回滚
  • 指定要在每个类或每个方法级别为每个测试加载的(DbUnit)数据集。应在事务启动后加载测试数据,以便在测试完成时回滚测试数据
  • 将Spring bean注入测试类

我知道Spring提供的类可以提供我正在寻求的事务行为。理想情况下,最终解决方案看起来像这样

// This dataset will be used for all tests that don't override it with their own annotation
@TestData('/dbunit/dataSetDefault.xml')
public class MyTests extends ProbablySomethingFromTheSpringFramework {

  @Test
  void testWithDefaultDataSet() {
    // Transaction is implicitly started here
    // My test code goes here
    // A transaction is implicitly rolled-back here    
  }

  @TestData('/dbunit/dataSetCustom.xml')
  @Test
  void testWithCustomDataSet() {
    // Same as the other test
  }
}

显然,父类和@TestData是虚构的,是否有可用的东西提供我正在寻找的功能?

这就留下了如何创建测试数据库模式的问题。理想情况下,这将在所有测试运行之前发生一次(由Maven)。有人可以建议我怎么做到这一点?我想它涉及使用某些东西将JPA注释转换为DDL,然后将其他东西加载到测试数据库模式中。

谢谢!

2 个答案:

答案 0 :(得分:4)

  

理想情况下,我希望能够:

     
      
  • 在之前创建测试数据库模式(来自JPA注释类)   测试运行
  •   

至少Hibernate可以从带注释的类创建数据库,我想其他的JPA实现也可以。

  
      
  • 在其自己的事务中运行每个测试方法,该事务在回滚时回滚   测试完成
  •   

在那里查看@TransactionConfiguration defaultRollback - 值,以及AbstractTransactionalJUnit4SpringContextTests(至少还有JUnit 3.8和TestNG的类似抽象类),请仔细看看javadocs中的参见 - 部分,它们指向许多非常有用的相关类和注释。

  
      
  • 指定要为每个测试加载的(DbUnit)数据集   每级或每个方法级别。该   应该在之后加载测试数据   交易已经开始了   测试数据也将被回滚   测试完成时
  •   

我实际上并没有使用过DbUnit,但至少使用JUnit,你可以使用@Before@BeforeClass分别在每个测试和类之前运行方法(还有@After和@AfterClass )。如果您有类层次结构,那么@ Before / @ BeforeClass -annotated方法将以扩展顺序运行(首先是baseclass)。有关运行sql脚本的信息,请参阅示例SimpleJdbcTestUtils

  
      
  • 将Spring bean注入测试类
  •   

AbstractTransactionalJUnit4SpringContextTests是ApplicationContextAware,另请参阅@ContextConfiguration进行设置。

最后,这里有一个简单的基础类我用来扩展我的实际集成测试(Spring 3,JUnit4,Hibernate作为JPA-provider,如果重要的话):

    //test-context, same as normal context, except uses H2 for in-memory database and has some stuff for faking session- and request-scope
    @ContextConfiguration(locations="classpath:applicationContext-test.xml") 
    @TransactionConfiguration(transactionManager="txManager", defaultRollback=true)
    @Transactional
    public abstract class IntegrationTestBase extends AbstractTransactionalJUnit4SpringContextTests
    {
        @PersistenceContext
        protected EntityManager em; 

        @Autowired
        protected SomeService serviceAvailableToSubclasses;

        @Before
        public void beforeEachTest()
        {
            //fill database with testdata and whatever you need to, runs before each test in extending classes
        }

        @After
        public void afterEachTest()
        {
            //Do something, if you need to, or just remove this
        }

    }

从此扩展,您可以在派生类中使用@ Transaction,@ Autowired等,或者派生出更具体的抽象测试基类(我有例如IntegrationSessionTestBase和IntegrationSessionNewRequestPerTestBase用于不同类型的测试,需要新的会话和/或每次测试的请求。)

答案 1 :(得分:1)

我已经使用基于JPA(Hibernate)的简单应用程序完成了这项工作。

<project
  xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.soebes.casestudy</groupId>
  <artifactId>casestudy</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>

  <name>Case Study Pizza Ordering</name>
  <url>Pizza Ordering</url>

  <properties>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <hibernate-core-version>3.4.0.GA</hibernate-core-version>
    <database.driverClassName>com.mysql.jdbc.Driver</database.driverClassName>
    <database.url>jdbc:mysql://localhost:3306/casestudy</database.url>
    <database.dialect>org.hibernate.dialect.MySQLDialect</database.dialect>
    <database.root.user>root</database.root.user>
    <database.root.password>root</database.root.password>

    <database.user>casestudy</database.user>
    <database.password>casestudy</database.password>

    <database.database>casestudy</database.database>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>hibernate3-maven-plugin</artifactId>
        <version>2.2</version>
        <executions>
          <execution>
            <id>hibernate-create-schema</id>
            <phase>generate-test-sources</phase>
            <goals>
              <goal>hbm2ddl</goal>
            </goals>
            <configuration>
              <components>
                <component>
                  <name>hbm2ddl</name>
                  <implementation>annotationconfiguration</implementation>
                </component>
              </components>
              <componentProperties>
                <configurationfile>/src/main/resources/hibernate.cfg.xml</configurationfile>
                <jdk5>true</jdk5>
                <packagename>com.soebes.casestudy.bo</packagename>
                <console>false</console>
                <outputfilename>create.sql</outputfilename>
                <drop>false</drop>
                <create>true</create>
                <update>false</update>
                <export>false</export>
                <format>true</format>
              </componentProperties>
            </configuration>
          </execution>
          <execution>
            <id>hibernate-drop-schema</id>
            <phase>generate-test-sources</phase>
            <goals>
              <goal>hbm2ddl</goal>
            </goals>
            <configuration>
              <components>
                <component>
                  <name>hbm2ddl</name>
                  <implementation>annotationconfiguration</implementation>
                </component>
              </components>
              <componentProperties>
                <configurationfile>/src/main/resources/hibernate.cfg.xml</configurationfile>
                <jdk5>true</jdk5>
                <packagename>com.soebes.casestudy.bo</packagename>
                <console>false</console>
                <outputfilename>drop.sql</outputfilename>
                <drop>true</drop>
                <create>false</create>
                <update>false</update>
                <export>false</export>
                <format>true</format>
              </componentProperties>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
          </dependency>
        </dependencies>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.8</version>
      </plugin>

     <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>sql-maven-plugin</artifactId>
        <version>1.4</version>

        <dependencies>
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
          </dependency>
        </dependencies>

        <!-- common configuration shared by all executions -->
        <configuration>
          <driver>${database.driverClassName}</driver>
          <url>${database.url}</url>
          <username>${database.root.user}</username>
          <password>${database.root.password}</password>
        </configuration>
        <executions>
          <execution>
            <id>drop-database</id>
            <phase>generate-test-resources</phase>
            <goals>
              <goal>execute</goal>
            </goals>
            <configuration>
              <sqlCommand>
              DROP DATABASE IF EXISTS casestudy;
              CREATE DATABASE casestudy;
              GRANT ALL ON casestudy.* TO ${database.user} IDENTIFIED BY '${database.password}';
              </sqlCommand>
            </configuration>
          </execution>
          <execution>
            <id>create-database</id>
            <phase>generate-test-resources</phase>
            <goals>
              <goal>execute</goal>
            </goals>
            <configuration>
              <sqlCommand>
              USE casestudy;
              </sqlCommand>
              <srcFiles>
                <srcFile>${project.build.directory}/hibernate3/sql/create.sql</srcFile>
              </srcFiles>
            </configuration>
          </execution>
        </executions>
      </plugin>

    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>${hibernate-core-version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>3.3.0.SP1</version>
    </dependency>
    <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.4.GA</version>
    </dependency>

    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>5.14.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.13</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.1</version>
    </dependency>
  </dependencies>
</project>