LoginSignup
1
0

More than 3 years have passed since last update.

初心者のためのJUnitテスト環境構築からのテスト実施(更新系まで)方法

Last updated at Posted at 2021-01-20

JUnitを使った単体テストの環境構築の備忘録です。JUunit5の環境構築に困っている方の参考になればと思います.

  1. pom.xmlに必要なDependencyを追加. ここでは、以下の3つを追加
    • 「JUnit」のバージョン5
    • Hamcrest(Assertionと呼ばれる値のチェックに使うメソッドのフレームワーク)
    • H2データベース(In-Memoryのデータベースを使うことで、ローカル環境にデータベースがなくてもテストできるようにする)
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <scope>test</scope>
        </dependency>

2. application.ymlを編集する.


spring:
  datasource:
    driverClassName: org.h2.Driver
    # "CLOSE_DELAY=-1"でテストを実行してから終了するまでの間、DBがある状態を作る設定
    url: jdbc:h2:mem:[あなたのDB名];DB_CLOSE_DELAY=-1 
    username: sa
    password:
  h2:
    console:
      enabled: true

  jpa:
    formatsql: true
    show_sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
      hbm2ddl:
        auto: none
    hibernate:
      ddl-auto: create

3.テストファイルを作成。 画像のように、「src/test/java/com/example/myApp」以下にフォルダ&Javaファイルを作成

スクリーンショット 2021-01-20 8.22.12.png
 
4. テスト用のデータを挿入するSQLファイルを作成。ファイルの作成場所は「テスト.java」と同じフォルダ 
スクリーンショット 2021-01-20 8.45.17.png
  ※5.で記述する@Sqlはデフォルトで同じフォルダ内にある、ファイル名が「テスト.java」の「.java」を「.sql」にしたファイルを探す

 
5. 「テスト.java」の中身を記述

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional
@Sql
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) //  メソッドごとにDBをリフレッシュする
@AutoConfigureTestDatabase(replace = Replace.ANY)
public class HogeTest { // テストしたいクラス名の後ろに"Test"をつける

  @Autowired
  private Repository repos; // テストしたいクラスをインポート

  @Autowired
  private JdbcTemplate jdbcTemplate; // 戻り値がvoidのメソッドが正しく機能したかをSELECTして確認するために使う

  @Test // 戻り値メソッドの場合
  public void testFindProduct() { 
    int id = 1;
    Product actual = repos.findProduct(id); // idでレコードを1つ取得するメソッドがあるとした場合
  // import static org.junit.jupiter.api.Assertions.assertTrue;
    assertTrue(actual != null); // 
  }

  @Test
  public void testUpdateUser() {
    int id = 1;
    String name = "updatedName";
    repos.updateUser(id, name) // 戻り値なしでidを条件に名前を変更するメソッドの場合
    String sql = "SELECT name FROM users WHERE id = ?";
    RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
    List<User> actual = jdbcTemplate.query(sql, rowMapper, id);
    assertEquals("updatedName", actual); // 変更した名前とメソッド実行後に取得した名前を比較して一致していることチェック

  }

}

6.テストを実行する。問題がなければ画像のようにデバッグコンソールにログが表示され、「✔️」がつく

スクリーンショット 2021-01-20 19.56.07.png

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