テストを動かすとInjectできなくてNullPointerExceptionで落ちる。くっそはまったのでメモ。
テスト対象クラス
@Component
public class TestService {
public int test() {
return 1;
}
}
JUnitの場合
@RunWith(SpringRunner.class)が抜けてました。
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestServiceTest2 {
@Autowired
private TestService sut;
@Test
public void _run_test() {
assert sut.test() == 1;
}
}
Spockの場合、@RunWithをつけるとエラーになります。
@RunWith(SpringRunner.class)
@SpringBootTest
class TestServiceSpec extends Specification {
@Autowired
private TestService sut
def "run test"() {
expect:
sut.test() == 1
}
}
java.lang.Exception: No runnable methods
Specificationを継承したクラスには@RunWithがつけられないようです。
Spockの場合
依存関係に以下を追加すること
// https://mvnrepository.com/artifact/org.spockframework/spock-spring
testCompile group: 'org.spockframework', name: 'spock-spring', version: '1.1-groovy-2.4'
そうすれば@SpringBootTestだけでテストできる。
個人的にはJUnitよりSpockを使いたいので、Spockを使う場合のbuild.gradleの設定をメモしておきます。
apply plugin: 'groovy'
...
/*
Groovy and Test Framework
*/
// https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all
testCompile group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.13'
// https://mvnrepository.com/artifact/org.spockframework/spock-core
testCompile group: 'org.spockframework', name: 'spock-core', version: '1.1-groovy-2.4'
// https://mvnrepository.com/artifact/org.spockframework/spock-spring
testCompile group: 'org.spockframework', name: 'spock-spring', version: '1.1-groovy-2.4'
...