LoginSignup
3
9

More than 5 years have passed since last update.

Spring Bootでテスト用のapplication.propertiesを読み込む

Last updated at Posted at 2017-02-14

テスト用にapplication.propertiesを用意して、テスト時にはそちらを読み込む。

src/resources/application.properties

app.name=props-app
app.comment=this is app:${app.name}

test/resource/application.properties

app.name=props-test
app.comment=this is test:${app.name}

@Valueでインジェクションする

PropsService.java

@Service
public class PropsService {
   @Value("${app.name}")
   private String appName;

   @Value("${app.comment}")
   private String appComment;

   public String getAppName() {
     return appName;
   }

   public String getComment() {
     return appComment;
   }
}

@ConfigurationPropertiesで読み込む

  • PropsConfig.java

@Component
@ConfigurationProperties(prefix = "app")
public class PropsConfig {
    private String name;
    private String comment;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }
}

  • PropsService.java
@Service
public class PropsService {
    @Autowired
    PropsConfig propsConfig;

    public String getAppName() {
        return propsConfig.getName();
    }

    public String getComment() {
        return propsConfig.getComment();
    }
}

テストコード

  • PropsServiceTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class PropsServiceTest {
    @Autowired
    PropsService service;

    @Test
    public void test_getAppName() {
        assertThat(service.getAppName()).isEqualTo("props-test");
    }

    @Test
    public void test_getComment() {
        assertThat(service.getComment()).isEqualTo("this is test:props-test");
    }
}

@SpringBootTestを入れ忘れて読み込まれなくて苦しんだ。

3
9
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
3
9