0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

📘 Vol.10.5:DAO・DTOのテスト設計(JUnitやH2活用)

Last updated at Posted at 2025-05-25

本記事では、DAO(Data Access Object)およびDTO(Data Transfer Object)のテスト設計について、JUnitH2データベース を活用した方法を解説します。


🧪 1. テストの目的と範囲

  • DAOのテスト:データベースとのやり取りが正しく行われているかを確認
  • DTOのテスト:データの受け渡しが正しく行われているかを確認

🛠 2. H2データベースの設定

H2は、インメモリで動作する軽量なRDB で、テスト用途に非常に適しています。

📦 Maven依存関係の追加

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

⚙ テスト用のデータソース設定例

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create

※Spring Boot 環境を想定していますが、純粋なJDBCでも DriverManager.getConnection("jdbc:h2:mem:testdb") のように使えます。


✅ 3. JUnitによるDAOのテスト

以下は、UserDao に対する基本的なテスト例です。

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {

    @Autowired
    private UserDao userDao;

    @Test
    public void testFindById() {
        User user = userDao.findById(1);
        assertNotNull(user);
        assertEquals("John", user.getUsername());
    }
}


📦 4. DTOのテスト

DTOはシンプルなデータ構造なので、ゲッター・セッターの動作確認が中心です。

@Test
public void testUserDto() {
    User user = new User();
    user.setUserId(1);
    user.setUsername("John");
    user.setEmail("john@example.com");

    assertEquals(1, user.getUserId());
    assertEquals("John", user.getUsername());
    assertEquals("john@example.com", user.getEmail());
}


🗃 5. テストデータの投入(data.sql)

src/test/resources/data.sql に以下のようなSQLを記述しておくと、テスト時に自動実行されます。

INSERT INTO users (user_id, username, email) VALUES (1, 'John', 'john@example.com');

これは、Spring Bootなどの環境で spring.jpa.hibernate.ddl-auto=create と組み合わせて利用します。


🧾 まとめ

項目 内容
H2 軽量なインメモリDB。JDBC互換で本番環境と似た動作確認が可能
JUnit DAO・DTOの挙動を自動化テスト
data.sql テスト用データを一括投入できる便利な仕組み

📌 次回予告:

📘 Vol.10.6:Service層の設計方針と例外処理戦略
→ DAO・DTOの上位層にあたる Service の設計と、例外処理(例:DB例外やバリデーション例外)の戦略について詳しく解説予定です!


🧵 過去シリーズ一覧

  • Vol.10.1:DTO設計のベストプラクティス

  • Vol.10.2:DAOのインタフェース設計と実装パターン

  • Vol.10.3:DB接続クラスの共通化とドライバ設計

  • Vol.10.4:Actionとの連携実装(Struts2との融合)

👍 お役に立てましたらLGTM&フォローお願いします!


✨ シリーズまとめ(Vol.10.x バリデーション編)


0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?