承前
Spring 2.x系で作成していたプロジェクトのテストに Spock Framework を採用していましたが、Spring 3系がリリースされましたので移行したところ、テストコードが軒並み失敗したためその対応方法を残しておきます。
採用していたプロジェクト構成
- SpringBoot 2.7.6
- MyBatis 3.x
- MySQL
- Spock framework
- Spock-Spring 2.3-groovy-4.0
- groovy-all 4.0.6
元々は MyBatisのPlugin機構 を検証する目的で作成したプロジェクトです。
テストコード例
ItemRepositoryTest.groovy
package com.github.apz.sample.repository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Specification
import spock.lang.Unroll
@SpringBootTest
@Unroll
class ItemRepositoryTest extends Specification{
@Autowired
ItemRepository itemRepository
def "検索テスト"() {
when:
def result = itemRepository.findById($id)
then:
result.size() == 1
result.get(0).getId() == _id
result.get(0).getName() == _name
where:
$id || _id | _name
'1' || 1L | '商品'
}
}
エラー原因
@Autowired
ItemRepository itemRepository
でSpringのテスト用ApplicationContextから自動的に取得できるはずの itemRepository が 得られません(nullになる=つまり @Autowired
が空振りしている)
結論
Spock framework のバージョンを修正します。
- spock-core:2.4-M1-groovy-4.0
- spock-spring:2.4-M1-groovy-4.0
サンプルプロジェクト