概要
データベースの更新処理(update)のユニットテストをどう書くか。
- テストデータを登録
- 更新処理を実施
- 更新内容が正しいか更新後のDBを参照してassert
「更新内容が正しいか更新後のDBを参照してassert 」で groovy.sql.Sql
を使ってみる
こんな感じ
@Unroll
@SpringBootTest
class SampleRepositorySpec extends Specification {
// DBを使ってるなら、DIコンテナに登録済と思う
@Autowired
DataSource dataSource
// テスト対象のリポジトリ
@Autowired
SampleRepository sampleRepository
// テストの実施
def "更新されること"() {
given:
// テストデータの登録や更新内容の準備など
when:
// 更新処理を実施
sampleRepository.update(sampleModel)
then:
// DataSourceを使ってSqlのインスタンス生成
def sql = new Sql(dataSource)
// 最初の一件だけ取得している
// Groovyはヒアドキュメントが使えるので、SQLは読みやすいように書ける
// バインドパラメータはリスト・配列・マップで渡せる(?.idのところ)
def result = sql.firstRow("""
select * from hoge
where id = ?.id
""", [id: 1])
// 更新内容のassert
assert result.COLUMN_NAME== '期待する更新値'
sql.close()
}
}
おまけ
いつものJavaな感じ(Groovyにそのまま書ける)
Connection conn = dataSource.getConnection()
Statement statement = conn.createStatement()
ResultSet resultSet = statement.executeQuery("select * from hoge")
resultSet.first()
resultSet.getObject("COLUMN_NAME") == "期待する更新値"
conn.close()
参考
http://docs.groovy-lang.org/latest/html/api/groovy/sql/Sql.html
http://d.hatena.ne.jp/nekozeoyaji/20150628/p1
http://npnl.hatenablog.jp/entry/20090505/1241504105
http://d.hatena.ne.jp/backpaper0/20110204/1296843674