Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

https://github.com/myahal/spring-property-test

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を入れ忘れて読み込まれなくて苦しんだ。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした