LoginSignup
1
1

More than 1 year has passed since last update.

data.sqlを使ってテストコードを簡略化してみる

Posted at

data.sqlとは

data.sqlを使用して、テストコードを簡略にしてみた。
data.sqlを使用すると、アプリケーションをロード時にテスト用とか初期にDBにqueryを実行したい時に役に立ちます。 data.sqlの配置パスは・・・src/resources/data.sql!

data.sql適用前

下のロジックではfindByBloodType()からgivenPerson()にてPerson Entityにデータを挿入して
ロジックを確認しています。

@Autowired
private PersonRepository personRepository;

@Test
void findByBloodType() {
    givenPerson("martin",10,"A");
    givenPerson("david",9,"B");
    givenPerson("dennis",8,"O");
    givenPerson("sophia",7,"AB");
    givenPerson("benny",6,"A");
   
    List<Person> result = personRepository.findByBloodType("A");

    assertThat(result.size()).isEqualTo(2);
    assertThat(result.get(0).getName()).isEqualTo("martin");
    assertThat(result.get(1).getName()).isEqualTo("benny");
}

private void givenPerson(String name, int age, String bloodType) {
    givenPerson(name, age ,bloodType, null);
}

private void givenPerson(String name, int age, String bloodType, LocalDate birthday) {
    Person person = new Person(name, age,bloodType);
    person.setBirthday(new Birthday(birthday));
    personRepository.save(person);
}

data.sql適用後

data.sqlにgivenPerson()にて登録したデータのinsert文を作成します。

src/resources/data.sql
insert into person(`id`, `name`, `age`,`blood_type`, `year_of_birthday`,`month_of_birthday`,`day_of_birthday`) values(1,'martin',10, 'A',null,null,null);
insert into person(`id`, `name`, `age`,`blood_type`, `year_of_birthday`,`month_of_birthday`,`day_of_birthday`) values(2,'david',9, 'B',null,null,null);
insert into person(`id`, `name`, `age`,`blood_type`, `year_of_birthday`,`month_of_birthday`,`day_of_birthday`) values(3,'dennis',8, 'O',null,null,null);
insert into person(`id`, `name`, `age`,`blood_type`, `year_of_birthday`,`month_of_birthday`,`day_of_birthday`) values(4,'sophia',7, 'AB',null,null,null);
insert into person(`id`, `name`, `age`,`blood_type`, `year_of_birthday`,`month_of_birthday`,`day_of_birthday`) values(5,'benny',6, 'A',null,null,null);

data.sqlに書いたdmlによりデータは作成されるので、givenPerson()は省くことができます。

@Autowired
private PersonRepository personRepository;

@Test
void findByBloodType() {
    List<Person> result = personRepository.findByBloodType("A");

    assertThat(result.size()).isEqualTo(2);
    assertThat(result.get(0).getName()).isEqualTo("martin");
    assertThat(result.get(1).getName()).isEqualTo("benny");
}

givenPerson()を削除して、data.sqlを適用した結果、問題なく確認できます。
image.png

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