项目在使用Maven进行自动化单元测试时,需要重新构建数据库并准备数据环境。准备了建库,建表和初始数据导入的sql脚本。可按以下sql-maven-plugin配置。
配置
在xxx-pom项目的pom.xml中配置sql-maven-plugin插件,供子项目使用(子项目如果需要使用,则在子项目pom中进行引用)。
在build > pluginManagement > plugins节点下配置
> XXX-POM配置
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<!---因为该实例中用到的数据库是mysql,故需依赖于mysql连接驱动 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
</dependencies>
<!--为该插件配置数据库连接信息 -->
<configuration>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306</url>
<username>root</username>
<password>root</password>
</configuration>
<executions>
<execution>
<id>create-db</id>
<phase>process-test-resources</phase><!-- 绑定到process-test-resources阶段 -->
<goals>
<goal>execute</goal>
</goals>
<configuration>
<autocommit>true</autocommit><!-- 使用事务,自动提交 -->
<srcFiles>
<srcFile>src/main/resources/create_db.sql</srcFile><!-- sql文件路径 -->
</srcFiles>
</configuration>
</execution>
<execution>
<id>create-table</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<autocommit>true</autocommit>
<srcFiles>
<srcFile>src/main/resources/create_table.sql</srcFile>
</srcFiles>
</configuration>
</execution>
<execution>
<id>insert-data</id>
<phase>process-test-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<orderFile>ascending</orderFile>
<fileset>
<basedir>${basedir}</basedir>
<includes>
<include>src/main/resources/init_data.sql</include>
</includes>
</fileset>
</configuration>
</execution>
</executions>
</plugin>
插件使用配置
如在xxx-service子项目中使用sql-maven-plugin插件,则在子项目的pom中配置如下:
XXX-SERVICE配置
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
</plugin>
</plugins>
</build>
使用
由于该插件配置中绑定了process-test-resources阶段,所以允许mvn test时,那些建库,建表,初始化数据的sql就会被执行。
运行记录:
> Maven输出
[INFO] --- sql-maven-plugin:1.5:execute (create-db) @ vocabulary-service ---
[INFO] Executing file: C:\Users\15070599\AppData\Local\Temp\create_db.1675254486sql
[INFO] 2 of 2 SQL statements executed successfully
[INFO]
[INFO] --- sql-maven-plugin:1.5:execute (create-table) @ vocabulary-service ---
[INFO] Executing file: C:\Users\15070599\AppData\Local\Temp\create_table.1203873535sql
[INFO] 3 of 3 SQL statements executed successfully
[INFO]
[INFO] --- sql-maven-plugin:1.5:execute (insert-data) @ vocabulary-service ---
[INFO] Executing file: E:\gitlib\cpfr\vocabulary\vocabulary-service\src\main\resources\init_data.sql
[INFO] 8 of 8 SQL statements executed successfully