Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
9
Help us understand the problem. What is going on with this article?
@hachi_eiji

便利なJdbcTestUtils

More than 5 years have passed since last update.

はじめに

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

9
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
hachi_eiji
Webエンジニアやってます
classi
学校の先生・生徒・保護者向けのB2B2Cの学習支援Webサービス「Classi(クラッシー)」 を開発・運営している会社です。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
9
Help us understand the problem. What is going on with this article?