LoginSignup
16
18

More than 5 years have passed since last update.

Spring Bootでテスト時に設定すること(まとめ中)

Posted at

使用しているVersion

Spring Boot 1.4.x
JUnit 4.x

JUnitクラスの設定

AutoWiredなどがあるクラスをテストする場合、JUnitなどのテスティングフレームワーク上でもSpringのDI機能を動かす必要があるため、そのアノテーションが必要になる。

Javadocによると、SpringRunnerという表記はよく見るSpringJUnit4ClassRunnerの別名であるので(SpringRunner is an alias for the SpringJUnit4ClassRunner.)これをアノテーションすれば良いそうである。

junit4test.java
@RunWith(SpringRunner.class)
public class XxxxTest {

もうひとつ。
DIのときにbean定義を@Configurationを付けたクラスで行っている場合は、それも指定しなくてはいけない。

junit4test.java
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class XxxxTest {

AppConfigクラスで、DI対象のクラスを全てDI出来るようになっていればOK。

AppConfig.java
@Configuration
@ComponentScan("com.xxx.repository") // DIしたいコンポーネントがあるpackage
public class AppConfig {

    @Bean
    XxxBean xxxBean(){
        xxxBean bean = new xxxBean();
        bean.setXxx(initialization data); // 何かの初期化
        return bean;
    }

16
18
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
16
18