はじめに
ユニットテストとかEnd to Endのテストでマスタデータを投入したい時に便利
対象環境
SpringFrameWork 3.2.8
使い方
こういうテーブルがあったとします
mysql> desc customer;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| first_name | varchar(255) | YES | | NULL | |
| last_name | varchar(255) | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
テストスクリプトを用意します。mysqldumpから取得した結果でもOK
resources/sql/insert-test.sql
insert into customer(id, first_name, last_name) value (1,"foo", "bar");
insert into customer(id, first_name, last_name) value (2,"foo", "bar");
insert into customer(id, first_name, last_name) value (3,"foo", "bar");
@Transactional
などは省略...
public class TestClientTest {
@Autowired
private DataSource dataSource;
@Test
public void test_readScriptPath() throws Exception {
// スクリプト実行する
executeScript("/sql/insert-test.sql");
// 行数を数える
int actual = JdbcTestUtils.countRowsInTable(new JdbcTemplate(dataSource), "customer");
assertThat("size is not match", actual, is(3));
}
private void executeScript(String... paths) throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
for (String path : paths) {
EncodedResource resource = new EncodedResource(new ClassPathResource(path, getClass()));
JdbcTestUtils.executeSqlScript(jdbcTemplate, resource, false);
}
}
}
最後に
Spring 4.0.3 からはアノテーションを使ったもっと便利な機能が追加されたみたいです。
Introduce annotation to execute SQL scripts in the TCF