8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

便利なJdbcTestUtils

Last updated at Posted at 2014-06-14

はじめに

ユニットテストとか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

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?